1

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.

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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]

1 Comment

Ah balls, I figured as much. =/ I'll give your function a go and see how it goes :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.