Home > Software engineering >  Populating a dictionary from a nested list
Populating a dictionary from a nested list

Time:10-16

So I have a list that nest list with pairs:

my_list = [[5,8],[5,10],[3,1],[10,18],[10,20],[21,30]

Now I want a dictionary that takes the first number as a key and then list all matching second numbers as value: so {3: [1], 5: [8,10], 10: [18,20], 21: [30]}

I already got a dictionary that consists of the necessary unique and sorted keys with empty values. How do populate this dictionary now with the correct values from the list?

CodePudding user response:

def foo(d, arr):
    for k, v in arr:
        if d.get(k):
            d[k].append(v)
        else:
            d[k] = [v]
            
d = {}
foo(d, my_list)
d
# {5: [8, 10], 3: [1], 10: [18, 20], 21: [30]}

CodePudding user response:

Using dict.setdefault we can dynamically create the internal structure inside of the new dictionary without having to care to check if the key inside of the dictionary exists already or not:

my_list = [[5, 8], [5, 10], [3, 1], [10, 18], [10, 20], [21, 30]]

d = {}
for key, value in my_list:
    d.setdefault(key, []).append(value)

print(d) # Output: {5: [8, 10], 3: [1], 10: [18, 20], 21: [30]}

CodePudding user response:

You can achieve this with map():

output = {}
def mapper(elem):
    values = output.get(elem[0], [])
    values.append(elem[1])
    output[elem[0]] = values
    return output

map(mapper, my_list)

As mentioned by @DeepSpace, this solution is not valid in Python 3.

  • Related