0

I'm a novice python programmer and I'm stuck on a homework problem.

I want to combine dictionaries (tried using **dict) without using the update() method because I want to keep any duplicate keys. I'm fine with having some keys with multiple values.

Could someone point me in the right direction?

Also, I'm doing this in python 3.3

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
  • Yes, I've seen the concatenate answer on this website, but that was just adding two dictionaries. – pythonintraining Sep 19 '13 at 04:43
  • 1
    duplicate keys are not possible in dict, you hash to same value – Grijesh Chauhan Sep 19 '13 at 04:44
  • Read: [How can I merge (union) two Python dictionaries in a single expression?](http://stackoverflow.com/questions/38987/how-can-i-merge-union-two-python-dictionaries-in-a-single-expression) – Grijesh Chauhan Sep 19 '13 at 04:45
  • I saw that, but again do not want to use update and i need to be able to combine indefinite number of dictionaries something similar to this: def newlist (*lists): new_list = [] for i in lists: new_list.extend(i) return set(new_list) – pythonintraining Sep 19 '13 at 04:50
  • Did you read answer? Many answer are without use of `update()` e.g. first – Grijesh Chauhan Sep 19 '13 at 04:51

2 Answers2

0

A dict maps a key to a value. Not multiple values. Thus, you need to make each value in the combined dict be a combination of all the values from the input dicts. The easiest way is to use a collections.defaultdict(list):

import collections

input_dicts = [{1: 0}, {1: 1}, {1: 2}]

output_dict = collections.defaultdict(list)
for d in input_dicts:
    for key in d:
        output_dict[key].append(d[key])

A collections.defaultdict calls a function you specify to generate a default value for any key that you try to access that doesn't already have a value. A collections.defaultdict(list) is thus a dict with default values of lists for all keys. This code will produce an output dict mapping keys to lists of all values from the input dicts.

user2357112
  • 260,549
  • 28
  • 431
  • 505
0

You can't have duplicate keys in a dictionary. The keys must be unique, but I think what you're looking for is a defaultdict

from collections import defaultdict
d = defaultdict(list)
d1 = {1:'hi', 2:'hey', 3:'hai'}
d2 = {1:'hello', 2:'cabbage', 3:'greetings'}
for k, v in d1.items():
    d[k].append(v)

for k1, v1 in d2.items():
    d[k1].append(v1)

print d

Prints:

defaultdict(<type 'list'>, {1: ['hi', 'hello'], 2: ['hey', 'cabbage'], 3: ['hai', 'greetings']})
user2357112
  • 260,549
  • 28
  • 431
  • 505
TerryA
  • 58,805
  • 11
  • 114
  • 143