fschuch
fschuch

Reputation: 27

Append dictionary values from another dictionary with the same keys

I have the following two dictionaries:

flow = {(49, 53): [122.92], (105, 34): [40.26], (47, 92): [85.28], ...} --- len(flow) = 134

dist= {(101, 15): 688, (47, 92): 156, (13, 62): 208, ...} --- len(dist) = 172

All the keys of flow are contained in dist (flow keys are a subset of dist keys), and I basically want to append all the distances in dist to the values of flow, to get the following:

flow_dist = {(49, 53): [122.92, 151], (105, 34): [40.26, 203], (47, 92): [85.28, 156], ...}

What I have so far:

list = [flow, dist]
new_dict = {key: [elem.get(key) for elem in list] for key in set().union(*list)}

Output: flow_dist = {(49, 53): [[122.92], 151], (105, 34): [[40.26], 203], (47, 92): [[85.28], 156], ...}

The problem is the values are [[value1], value2] instead of [value1, value2].

Can someone help? Appreciate it.

Upvotes: 0

Views: 103

Answers (2)

Fractal
Fractal

Reputation: 814

flow_dist = flow.copy()
for x in flow:
    if x in dist:
        flow_dist[x].append(dist[x])

Upvotes: 1

Carles Mitjans
Carles Mitjans

Reputation: 4866

Something like this should work:

{key: [value] + flow.get(key, []) for key, value in dist.items()}

Example:

In [11]: dist
Out[11]: {(101, 15): 688, (47, 92): 156, (13, 62): 208}

In [12]: flow
Out[12]: {(49, 53): [122.92], (105, 34): [40.26], (47, 92): [85.28]}

In [13]: {key: [value] + flow.get(key, []) for key, value in dist.items()}
Out[13]: {(101, 15): [688], (47, 92): [156, 85.28], (13, 62): [208]}

Upvotes: 4

Related Questions