Convert python list into dictionary by mapping list elements to themselves

Question:

If I have a list that looks like this:

['1 184',
 '1 29',
 '1 31',
 '1 12',
 '1 51',
 '1 102',
 '1 13',
 '1 14',
 '1 15',
 '1 57',
 '1 378',
 '1 859',
 '1 185',
 '1 30',
 '1 37',
 '1 52',
 '1 142',
 '1 195',
 '1 875',
 '1 56',
 '1 66',
 '1 95',
 '1 462',
 '1 497',
 '1 858',
 '1 876',
 '1 879',
 '1 880',
 '2 12',
 '2 15',
 '2 184',
 '2 858',
 '2 51']

And I wanted to map the first element of each string to each of the next elements tied to that first number, and get it in the format of {1 : [184, 29, 31...], 2 : [12, 15, 18, ...]}.

How could I do that?

Asked By: Julien

||

Answers:

If lst is your list from your question then:

out = {}
for a, b in map(str.split, lst):
    out.setdefault(int(a), []).append(int(b))

print(out)

Prints:

{
    1: [
        184,
        29,
        31,
        12,
        51,
        102,
        13,
        14,
        15,
        57,
        378,
        859,
        185,
        30,
        37,
        52,
        142,
        195,
        875,
        56,
        66,
        95,
        462,
        497,
        858,
        876,
        879,
        880,
    ],
    2: [12, 15, 184, 858, 51],
}

EDIT: To explicitly check for correct values:

out = {}
for value in lst:
    value = value.split()
    if len(value) == 2:
        a, b = value
        out.setdefault(int(a), []).append(int(b))
Answered By: Andrej Kesely

I think I understand your question. Does this solve it?

Dictionary = dict() # You must use `dict()` for an empty dictionary because if you write "{}", Python will think it's a set

# Loop through each value in `x`
for Value in x:
    # Get the Key and Value for the Dictionary
    Key,Value = Value.split(" ")

    # If the dictionary's value at key: `Key` has not been set, it will raise a KeyError once called. If this is the case, you must create a blank list for the Value in `Key`
    try:
        Dictionary[Key]
    except KeyError:
        Dictionary[Key] = []

    # Add the Value to the Dictionary at `Key`
    Dictionary[Key].append(Value)

Note: x is the list() in the question

Answered By: Daniel

Another possible solution, based on the creation of a pandas dataframe:

(pd.DataFrame
 .from_records([list(map(int, x.split())) for x in l], columns=list('ab'))
 .groupby('a')['b'].apply(list).to_dict())

Output:

{1: [184, 29, 31, 12, 51, 102, 13, 14, 15, 57, 378, 859, 185, 30, 37, 
52, 142, 195, 875, 56, 66, 95, 462, 497, 858, 876, 879, 880], 
2: [12, 15, 184, 858, 51]}
Answered By: PaulS

I would just use a defauldict with list values

from collections import defaultdict

res = defaultdict(list)
for item in data:
    k, v = item.split()
    res[int(k)].append(int(v))
Answered By: DevLounge
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.