Hell Man
Hell Man

Reputation: 873

How can you get a python dictionary to have duplicate keys holding values?

I'm working on an assignment. Is there anyway a dictionary can have duplicate keys and hold the same or different values. Here is an example of what i'm trying to do:

dict = {
        'Key1' : 'Helo', 'World'
        'Key1' : 'Helo'
        'Key1' : 'Helo', 'World'
       }

I tried doing this but when I associate any value to key1, it gets added to the same key1. Is this possible with a dictionary? If not what other data structure I can use to implement this process?

Upvotes: 0

Views: 3367

Answers (3)

Kyle Kelley
Kyle Kelley

Reputation: 14144

Use dictionaries of lists to hold multiple values.

One way to have multiple values to a key is to use a dictionary of lists.

x = { 'Key1' : ['Hello', 'World'],
      'Key2' : ['Howdy', 'Neighbor'],
      'Key3' : ['Hey',   'Dude']
    }

To get the list you want (or make a new one), I recommend using setdefault.

my_list = x.setdefault(key, [])

Example:

>>> x = {}
>>> x['abc'] = [1,2,3,4]
>>> x
{'abc': [1, 2, 3, 4]}
>>> x.setdefault('xyz', [])
[]
>>> x.setdefault('abc', [])
[1, 2, 3, 4]
>>> x
{'xyz': [], 'abc': [1, 2, 3, 4]}

Using defaultdict for the same functionality

To make this even easier, the collections module has a defaultdict object that simplifies this. Just pass it a constructor/factory.

from collections import defaultdict
x = defaultdict(list)
x['key1'].append(12)
x['key1'].append(13)

You can also use dictionaries of dictionaries or even dictionaries of sets.

>>> from collections import defaultdict
>>> dd = defaultdict(dict)
>>> dd
defaultdict(<type 'dict'>, {})
>>> dd['x']['a'] = 23
>>> dd
defaultdict(<type 'dict'>, {'x': {'a': 23}})
>>> dd['x']['b'] = 46
>>> dd['y']['a'] = 12
>>> dd
defaultdict(<type 'dict'>, {'y': {'a': 12}, 'x': {'a': 23, 'b': 46}})

Upvotes: 3

Back2Basics
Back2Basics

Reputation: 7806

Keys are unique to the data. Consider using some other value for a key or consider using a different data structure to hold this data.

for example:

  • don't use a persons address as a unique key because several people might live there.
  • a person's social security number or a drivers license is a much better unique id of a person.
  • you can create your own id to force it to be unique.

Upvotes: 0

TerryA
TerryA

Reputation: 59984

I think you want collections.defaultdict:

from collections import defaultdict
d = defaultdict(list)
list_of_values = [['Hello', 'World'], 'Hello', ['Hello', 'World']]
for v in list_of_values:
    d['Key1'].append(v)

print d

This will deal with duplicate keys, and instead of overwriting the key, it will append something to that list of values.

Upvotes: 0

Related Questions