简体   繁体   中英

Python dictionary values merging based on specific key

I want to merge two CSV files that I have read into python using the following code,

a = csv.DictReader(csv1)
b = csv.DictReader(csv2)

aMap = {}
bMap = {}

for row in a:
    aMap[row['id']] = row

for row in b:
    bMap[row['id']] = row

Now I should have two dictionaries whose keys are the 'id' field from the two CSVs. What I want to do is take everything from the aMap and add the values to the corresponding key values to bMap. For example in aMap, a key in the dictionary looks like this,

'123456' : {'name': 'SomeName', 'type': 'someType'}

And what I have in bMap is

'123456' : {'location' : 'someLocation'}

And what I want is,

'123456' : {'location' : 'someLocation', 'name' : 'SomeName', 'type' : 'someType'}

Is there a specific function for this or do I have to create a new dictionary? Something similar to update() but just appending values instead of updating.

You could use one collections.defaultdict , and use update to merge rows from csv2.

import collections

aMap = collections.defaultdict(dict)

for row in csv.DictReader(csv1):
    aMap[row['id']] = row

for row in csv.DictReader(csv2):
    aMap[row['id']].update(row)

I don't think there is a builtin function for that. So you'll have to do something like

def AppendToValues(from_map, to_map):
  for key in from_map:
    to_map[key] = to_map.get(key, {})
    to_map.update(from_map.get(key, {}))

To delete key, value from map:

del my_map[key]

I believe you can use the defaultdict in the collections module for this. http://docs.python.org/library/collections.html#collections.defaultdict

I think the examples are pretty close to being exactly what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM