Home > Net >  How to merge multiple values in a same dictionary?
How to merge multiple values in a same dictionary?

Time:04-07

I have two dictionaries x and y, which consist of keys and values.

x (its 'values') showing the address (which I want to merge in y).

y represents the dictionary whose 'values', I want to merge.

For example: x = { 1: [1,2], ...} i.e., I want to merge 1st and 2nd 'values' of y dictionary.

So desired output will be [0,1,2,3].

Similarly for 4:[2,5] it is [2,3,29,30,31].

Is it possible to do this operation in python and finally brought this result into a separate list for each value of y?

x = { 1:[1,2], 2:[2,3], 3:[3,4], 4:[2,5]} 

y = { 1:[0,1], 2:[2,3], 3:[4,5], 4:[6,7], 5:[29,30,31]  }

Desired output:

[0,1,2,3]
[2,3,4,5]
[4,5,6,7]
[2,3,29,30,31]

CodePudding user response:

One-liner

my_list = [[j for s in x[i] for j in y[s]] for i in x]

Longer but perhaps more readable

x = {1: [1,2], 2: [2,3], 3: [3,4], 4: [2,5]}

y = {1: [0,1], 2: [2,3], 3: [4,5], 4: [6,7], 5: [29,30,31]}

my_list = []

for i in x:
    temp = []
    my_list.append(temp)
    for j in x[i]:
        temp.extend(y[j])

print(my_list)

For complicated list comprehensions I prefer explicitly writing out loops for improved readability. Whether one snippet is more readable than another is of course a matter of opinion.

Output

[[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [2, 3, 29, 30, 31]]

I hope it helps. If there are any questions or if this is not what you wanted, please let me know!

CodePudding user response:

You actually only need one line:

[sum([y[index] for index in v], start=[]) for k, v in x.items()]

This gives:

[[0, 1, 2, 3], [2, 3, 4, 5], [4, 5, 6, 7], [2, 3, 29, 30, 31]]

If you want to print all of the sub-lists:

for k, v in x.items():
    print(sum([y[index] for index in v], start=[]))

Outputs:

[0, 1, 2, 3]
[2, 3, 4, 5]
[4, 5, 6, 7]
[2, 3, 29, 30, 31]
  • Related