Home > OS >  Map Python list elements to themselves
Map Python list elements to themselves

Time:09-01

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 number, and get it in the format of {1 : [184, 29, 31...], 2 : [12, 15, 18, ...]}.

How could I do that?

CodePudding user response:

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))

CodePudding user response:

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

CodePudding user response:

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]}
  • Related