Rahul Sharma
Rahul Sharma

Reputation: 2495

Map a dictionary on a list of dictionaries

I have a dictionary Items

Items = {1: 1, 2: 2, 3: 2, 4: 2, 5: 2, 6: 3, 7: 4, 8: 5}

I want to map the values of Items on a list of dictionaries named loaded

loaded = [{6: [4, 1, 3]}, {1: [5]}, {10: [8, 6]}, {6: [7]}, {2: [2]}]

such that I get this as my outcome:

u_loaded = [{6: [2, 1, 2]}, {1: [2]}, {10: [5, 3]}, {6: [4]}, {2: [2]}]

I tried running loops and replacing the values if a match is found but it's not working

for i in loaded_list:
    for k,v in i.items():
        for j in v:
            for a,b in pid_itemid_dic.items():
                if j==a:
                    j=b

Upvotes: 0

Views: 140

Answers (4)

olivaw
olivaw

Reputation: 373

You may want to avoid loops in order to adopt a Pythonic style. What you would like to do can be achieved in just one line:

u_loaded = [{k: [Items[i] for i in v] for k, v in d.items()} for d in loaded]

It is using list comprehension to loop over all dictionaries in loaded. And then, it follows a loop over the dictionaries keys k and values v to reconstruct the dictionary you want to create.

Upvotes: 0

gmds
gmds

Reputation: 19905

You can use a simple list comprehension:

result = [{k: [Items[v] for v in l] for k, l in d.items()} for d in loaded]
print(result)

Output:

[{6: [2, 1, 2]}, {1: [2]}, {10: [5, 3]}, {6: [4]}, {2: [2]}]

This is equivalent to the following for loop:

result = []

for d in loaded:
    new_sub_dict = {}
    for k, l in d.items():
        new_sub_list = []
        for v in l:
            new_sub_list.append(Items[v])
        new_sub_dict[k] = new_sub_list
    result.append(new_sub_dict)

Upvotes: 1

Paritosh Singh
Paritosh Singh

Reputation: 6246

One step at a time, you can approach it in the following manner.

loaded = [{6: [4, 1, 3]}, {1: [5]}, {10: [8, 6]}, {6: [7]}, {2: [2]}]

Items = {1: 1, 2: 2, 3: 2, 4: 2, 5: 2, 6: 3, 7: 4, 8: 5}

u_loaded = [{k: [Items[val] for val in v] for k,v in d.items()} for d in loaded]

For an Explanation of 1 liner, we can open it up:

u_loaded = [] #stores the list of dicts
for d in loaded:
    u_d = {} #create empty result dict
    for k,v in d.items():
        u_d[k] = [Items[val] for val in v] #for every value, take the corresponding mapping result from loaded
    u_loaded.append(u_d) #append the dictionary to the result list

Output:

[{6: [2, 1, 2]}, {1: [2]}, {10: [5, 3]}, {6: [4]}, {2: [2]}]

Upvotes: 2

Nithin
Nithin

Reputation: 1105

u_loaded = [{k:[Items[a] for a in v] for k,v in l.items()} for l in loaded]
print(u_loaded)

Output

[{6: [2, 1, 2]}, {1: [2]}, {10: [5, 3]}, {6: [4]}, {2: [2]}]

Upvotes: 2

Related Questions