I want to merge this dictionary:
b = {data:[{station_id: 7000,
name: "Ft. York / Capreol Crt."
},
{station_id: 7001,
name: "Lower Jarvis St / The Esplanade"}
]}
and this one :
c = {data:[{station_id: 7000,
num_bikes_available: 18,
},
{station_id: 7001,
num_bikes_available: 4,
}
]}
and get one dictionary like this:
d = {data:[{station_id: 7000,
name: "Ft. York / Capreol Crt.",
num_bikes_available: 18
},
{station_id: 7001,
name: "Lower Jarvis St / The Esplanade",
num_bikes_available: 4}
]}
How can I do that?
chepner
538k77 gold badges594 silver badges746 bronze badges
2 Answers 2
For Py>3.5:
It's easy. Just enter:
d = {**b, **c}
Sign up to request clarification or add additional context in comments.
7 Comments
Root
I only know how to use Py3. :p
cs95
@Root You should know that there are solutions that work on python3 as well as python2.
AChampion
I would note that in your answer - also note this in only Py>3.5.
Root
Good advice. I will add it.
Robφ
@root, have you run this with the sample data? Does this give the answer OP expects?
|
The key to this problem is picking the right data structure. Instead of b['data'] being a list, it should be a dict indexed by the merge key. The following code first converts b and c into dicts indexed by station_id, then merges those dictionaries.
Try this:
from pprint import pprint
b = {'data': [{'station_id': 7000,
'name': "Ft. York / Capreol Crt."
},
{'station_id': 7001,
'name': "Lower Jarvis St / The Esplanade"},
{'station_id':7002,'num_bikes_available':10},
]}
c = {'data': [{'station_id': 7000,
'num_bikes_available': 18,
},
{'station_id': 7001,
'num_bikes_available': 4,
}
]}
# First, convert B and C to a more useful format:
b1 = {item['station_id']: item for item in b['data']}
c1 = {item['station_id']: item for item in c['data']}
# Now construct D by merging the individual values
d = {'data': []}
for station_id, b_item in sorted(b1.items()):
z = b_item.copy()
z.update(c1.get(station_id, {}))
d['data'].append(z)
pprint(d)
answered Jul 20, 2017 at 2:04
Robφ
170k20 gold badges251 silver badges323 bronze badges
2 Comments
kia
But what if for example in b there was also {'station_id':7002,'num_bikes_available':10} which in c there isn't. what about then??
Robφ
Anytime you need an item from a dictionary, but it might not be present, use
dict.get(). I have modified the z.update(...) line in response to your question.lang-py
d = dict(b); d.update(c)bto a dict?b, so theupdate()doesn't changeb.data,station_idetc are strings?)