0

I am trying to parse some data from a file which has two attributes a first name and country. The file is large and I was trying to store these attributes in a dictionary however this is automatically filtering the key values and I need all the duplicates as I plan to perform operations on the data which involve the duplicate values( simplified example below)

dictionary={"John":"Ireland","John":"Ireland"}

Is there anyway of getting around this ?

NeptuneGamer
  • 123
  • 1
  • 12
  • 5
    No, there's isn't - dictionary keys **must be unique**, due to the underlying hash table implementation. You will need a different structure, e.g. a list of tuples `[('John', 'Ireland'), ...]`. – jonrsharpe Oct 21 '15 at 16:15
  • 1
    you could have the keys point to lists but as @jonrsharpe has said, they keys must be unique – R Nar Oct 21 '15 at 16:17

1 Answers1

0

Keys in a dictionary have to be unique, but one option is to use a defaultdict with lists for each key:

In [74]: from collections import defaultdict

In [75]: d = defaultdict(list)

In [76]: for i, j in zip([1,2,1,1,2,3,1], [4,4,3,3,1,2,2]):
   ....:     d[i].append(j)
   ....:

In [77]: d
Out[77]: defaultdict(list, {1: [4, 3, 3, 2], 2: [4, 1], 3: [2]})
Randy
  • 14,349
  • 2
  • 36
  • 42