Make a dictionary with duplicate keys in Python

how many identical keys can a dictionary have in python
python dictionary same key multiple values
python ordered dict with duplicate keys
python list of dictionaries find duplicates based on value
python dictionary unique keys
can a dictionary have duplicate keys
repeated keys python
python json duplicate keys

I have the following list which contains duplicate car registration numbers with different values. I want to convert it into a dictionary which accepts this multiple keys of car registration numbers.

So far when I try to convert list to dictionary it eliminates one of the keys. How do I make a dictionary with duplicate keys?

The list is:

EDF768, Bill Meyer, 2456, Vet_Parking
TY5678, Jane Miller, 8987, AgHort_Parking
GEF123, Jill Black, 3456, Creche_Parking
ABC234, Fred Greenside, 2345, AgHort_Parking
GH7682, Clara Hill, 7689, AgHort_Parking
JU9807, Jacky Blair, 7867, Vet_Parking
KLOI98, Martha Miller, 4563, Vet_Parking
ADF645, Cloe Freckle, 6789, Vet_Parking
DF7800, Jacko Frizzle, 4532, Creche_Parking
WER546, Olga Grey, 9898, Creche_Parking
HUY768, Wilbur Matty, 8912, Creche_Parking
EDF768, Jenny Meyer, 9987, Vet_Parking
TY5678, Jo King, 8987, AgHort_Parking
JU9807, Mike Green, 3212, Vet_Parking

The code I have tried is:

data_dict = {}
data_list = []

def createDictionaryModified(filename):
  path = "C:\Users\user\Desktop"
  basename = "ParkingData_Part3.txt"
  filename = path + "//" + basename
  file = open(filename)
  contents = file.read()
  print contents,"\n"
  data_list = [lines.split(",") for lines in contents.split("\n")]
  for line in data_list:
    regNumber = line[0]
    name = line[1]
    phoneExtn = line[2]
    carpark = line[3].strip()
    details = (name,phoneExtn,carpark)
    data_dict[regNumber] = details
  print data_dict,"\n"
  print data_dict.items(),"\n"
  print data_dict.values()

Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.

One easy way to achieve this is by using defaultdict:

from collections import defaultdict

data_dict = defaultdict(list)

All you have to do is replace

data_dict[regNumber] = details

with

data_dict[regNumber].append(details)

and you'll get a dictionary of lists.

How to create Python dictionary with duplicate keys?, Dictionaries do not support duplicate keys. However, more than one value can correspond to a single key using a list. For example, with the dictionary {"a": [1  Python | Find keys with duplicate values in dictionary. Given a dictionary, the task is to find keys with duplicate values. Let’s discuss a few methods for the same. Method #1: Using Naive approach. In this method first, we convert dictionary values to keys with the inverse mapping and then find the duplicate keys. # Python code to demonstrate.

You can change the behavior of the built in types in Python. For your case it's really easy to create a dict subclass that will store duplicated values in lists under the same key automatically:

class Dictlist(dict):
    def __setitem__(self, key, value):
        try:
            self[key]
        except KeyError:
            super(Dictlist, self).__setitem__(key, [])
        self[key].append(value)

Output example:

>>> d = dictlist.Dictlist()
>>> d['test'] = 1
>>> d['test'] = 2
>>> d['test'] = 3
>>> d
{'test': [1, 2, 3]}
>>> d['other'] = 100
>>> d
{'test': [1, 2, 3], 'other': [100]}

How to make a dictionary with duplicate keys in Python, Short answer, no. If you want to have a system similar to duplicate keys, you can make a two-dimensional array, For a more elegant system that supports  Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary. One easy way to achieve this is by using defaultdict: from collections import defaultdict data_dict = defaultdict(list) All you have to do is replace. data_dict[regNumber] = details with. data_dict[regNumber].append(details)

You can't have a dict with duplicate keys for definition! Instead you can use a single key and, as value, a list of elements that had that key.

So you can follow these steps:

  1. See if the current element's (of your initial set) key is in the final dict. If it is, go to step 3
  2. Update dict with key
  3. Append the new value to the dict[key] list
  4. Repeat [1-3]

Can the Python dictionary have duplicate keys?, By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Given a dictionary, the task is to find keys with duplicate values. Python code to demonstrate. # finding duplicate values from a dictionary. A dictionary, by definition, requires that keys be unique identifiers. You can either: Use a different data structure such as a list or tuple that allows for duplicate entries. Use a unique identifier for your dictionary keys, much the same way that a database might use an auto-incrementing field for its key id.

You can't have duplicated keys in a dictionary. Use a dict of lists:

for line in data_list:
  regNumber = line[0]
  name = line[1]
  phoneExtn = line[2]
  carpark = line[3].strip()
  details = (name,phoneExtn,carpark)
  if not data_dict.has_key(regNumber):
    data_dict[regNumber] = [details]
  else:
    data_dict[regNumber].append(details)

Python, This means that if a key is duplicated the second key-value pair will overwrite the first as a dictionary can only have one value per key. Recommendation. Check for  Convert list to dictionary with duplicate keys using dict comprehension. Removing duplicates in lists. 1611. How to remove a key from a Python dictionary?

If you want to have lists only when they are necessary, and values in any other cases, then you can do this:

class DictList(dict):
    def __setitem__(self, key, value):
        try:
            # Assumes there is a list on the key
            self[key].append(value)
        except KeyError: # If it fails, because there is no key
            super(DictList, self).__setitem__(key, value)
        except AttributeError: # If it fails because it is not a list
            super(DictList, self).__setitem__(key, [self[key], value])

You can then do the following:

dl = DictList()
dl['a']  = 1
dl['b']  = 2
dl['b'] = 3

Which will store the following {'a': 1, 'b': [2, 3]}.


I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:

my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
    rev_med[v] = k

Which will generate the same output as above: {'a': 1, 'b': [2, 3]}.


CAVEAT: This implementation relies on the non-existence of the append method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,

dl = DictList()
dl['a']  = 1
dl['b']  = [2]
dl['b'] = 3

would produce the same result as before {'a': 1, 'b': [2, 3]}, but one might expected the following: {'a': 1, 'b': [[2], 3]}.

Duplicate key in dict literal - Python queries, With a dict in Python (like a hash in Perl or an associative array in PHP), it's peceived wisdom that you can only have one element with a paricular  Looking up a value by key - associative arrays / Hashes / Dictionaries - (2010-08-11) Python - fresh examples of all the fundamentals - (2009-08-20) Using a list of keys and a list of values to make a dictionary in Python - zip - (2007-04-13) Python dictionary for quick look ups - (2007-04-12)

Multiple identical keys in a Python dict, make dictionary with duplicate keys in python. I have the following list which contains duplicate car registration numbers with different values. I want to convert it  If you wish to create a Python dictionary with fixed keys and values, then it’s quite easy to do so. Just combine all the “key1:value1, key2:value2,…” pairs and enclose with curly braces. The combination of a key and its value, i.e. “key: value” represents a single element of a dictionary in Python.

make dictionary with duplicate keys in python, Question Can a dictionary have two keys with the same value? Answer No, each key in a dictionary should be unique. You can't have two keys  Python dictionary method keys() returns a list of all the available keys in the dictionary. Syntax. Following is the syntax for keys() method − dict.keys() Parameters. NA. Return Value. This method returns a list of all the available keys in the dictionary. Example. The following example shows the usage of keys() method.

Can a dictionary have two keys of the same value?, A big caution here is that you cannot create different values with the same key. Python will just overwrite the value of the duplicate keys. With all of the warnings​  Python : How to add / append key value pairs in dictionary using dict.update() Python : How to Remove multiple keys from Dictionary while Iterating ? Python : How to convert a list to dictionary ? Python : How to check if a key exists in dictionary ? Python : How to find keys by value in dictionary ? How to Merge two or more Dictionaries in

Comments
  • If a dictionary allowed duplicate keys with different associated values, which one would you expect to to be retrieved when you look up the value for such a key later?
  • I didn't, at first, understand that this is equivalent to declaring the dictionary key's value as a list yourself and appending to it. Eliminates a few lines of boilerplate though, which is nice. if not my_key in data_dict: data_dict[my_key] = list()
  • Why not just if key not in self: instead of try:/except KeyError:?
  • Is this not the same as: 'from collections import defaultdict d = defaultdict(list) d['test'].append(1) d['test'].append(2) d['test'].append(3)' Or may I missing out something?
  • But the defaultdict solution is better than doing this manually (aix's answer)
  • instead of hash_key, we can just use if not regNumber in data_dict
  • Yes, not in is better and indeed there is no hash_key method in Python 3.x. Thanks!
  • How to get all values with the key 'k'? The only way to do this is sequential comparing, which loses the meaning of using a hash dictionary.
  • Clean and elegant answer. Thanks! The corollary is that, if you're already planning to use objects then you don't need to do anything. See full example using OrderedDict: stackoverflow.com/a/56959984/1732392
  • @minion is right here. Either you store references to those objects to access the values, or you have to iterate. In the former case you might as well just put the data in the key object and forget the dictionary, in the latter case you can just use a list of tuples. This doesn't really do what it says on the tin - you are just making the keys different. That might solve your problem, but at that point, the dictionary becomes the wrong data structure and you just have a layer of indirection you don't need.