-3

Hi, I want to merge two lists into one dictionary. Suppose I have two lists such as below

list_one = ['a', 'a', 'c', 'd']

list_two = [1,2,3,4]

and I want my dictionary to be like this

{'a': 1, 'a': 2, 'c': 3, 'd': 4}

As of right now, I have this following code

print dict(zip(['a', 'a', 'c', 'd'], [1,2,3,4]))

But the output from above code is this

{'a': 2, 'c': 3, 'd': 4}

How can I make it to this output?

{'a': 1, 'a': 2, 'c': 3, 'd': 4}

Thanks

6
  • This is simply impossible.
    – Julien
    Commented Dec 12, 2017 at 4:10
  • @Julien Maybe not in Python with its dictionaries, but dictionaries with duplicate entries for the same key are possible. Balanced trees like Red-Black can handle it and provide range queries, like find the lowest or highest duplicate key, etc.
    – Kaz
    Commented Dec 12, 2017 at 4:12
  • @Kaz, maybe but here OP is talking about python dict...
    – Julien
    Commented Dec 12, 2017 at 4:13
  • @Julien I see, so is there any way in python that I can do a mapping function to get my desired ouput like above? Commented Dec 12, 2017 at 4:17
  • This simply is impossible because your question makes no sense: as said by @Sebastian what is the mapping of 'a'??? 1 or 2? or should it be [1,2]? you need to clarify...
    – Julien
    Commented Dec 12, 2017 at 4:20

8 Answers 8

8

Since keys in dictionaries are unique, getting {'a': 1, 'a': 2, 'c': 3, 'd': 4} is impossible here for regular python dictionaries, since the key 'a' can only occur once. You can however have a key mapped to multiple values stored in a list, such as {'a': [1, 2], 'c': [3], 'd': [4]}.

One option is to create a defaultdict to do this easily for you:

from collections import defaultdict

list_one = ['a', 'a', 'c', 'd']

list_two = [1, 2, 3, 4]

d = defaultdict(list)
for key, value in zip(list_one, list_two):
    d[key].append(value)

print(dict(d))

Which outputs:

{'a': [1, 2], 'c': [3], 'd': [4]}
0
6

A defining characteristic of dicts is that each key is unique. Thus, you can't have two 'a' keys. Otherwise, what would my_dict['a'] return?

4
  • 1
    The question "what would my_dict['a'] return" actually has some reasonable answers. A requirement can be given in this area, for a dictionary that is intended to support multiple entries. C++ has a std::multiset dictionary type which supports a find function and [] indexing. Basically these return one of the duplicate keys; it is not specified which. There is a reliable way to iterate over the whole range of duplicate keys. I.e. a rhetorical question suggesting that a requirement is not reasonable isn't really the answer; it's just not the way a dict is in Python, that's all.
    – Kaz
    Commented Dec 12, 2017 at 4:14
  • Ah I see, so then this would be impossible to do right? Commented Dec 12, 2017 at 4:15
  • @IqbalPratama Impossible directly. However, the Python dict certainly can be used to write code which associates multiple values with the same key. Just associate keys with lists of values rather than values. Concretely speaking, {'a': [1, 2], 'c': [3], 'd': [4]}.
    – Kaz
    Commented Dec 12, 2017 at 4:18
  • @IqbalPratama depends on what you would want my_dict['a'] to return. Commented Dec 12, 2017 at 4:34
6

Dictionaries must have unique keys, so you would have to change your requirement. How about a list of tuples as a workaround?

l = list(zip(['a', 'a', 'c', 'd'],[1,2,3,4]))
print(l)

With the resulting being:

[('a', 1), ('a', 2), ('c', 3), ('d', 4)]

You can easily iterate over and unpack like so:

for k, v in l:
    print("%s: %s" % (k, v))

which produces:

a: 1
a: 2
c: 3
d: 4

If you want it hashable, you can create a tuple of tuples like so:

l = tuple(zip(['a', 'a', 'c', 'd'],[1,2,3,4]))
2
  • it's getting an error -> TypeError: unhashable type: 'list' Commented Dec 12, 2017 at 7:19
  • I updated my answer to show how to create a tuple of tuples. Commented Dec 12, 2017 at 22:49
2

You have two options :

either you use tuple :

list_one = ['a', 'a', 'c', 'd']

list_two = [1,2,3,4]



print(list(map(lambda x,y:(x,y),list_one,list_two)))

output:

[('a', 1), ('a', 2), ('c', 3), ('d', 4)]

Second option is use this pattern:

dict_1={}

for key,value in zip(list_one,list_two):
    if key not in dict_1:
        dict_1[key]=[value]
    else:
        dict_1[key].append(value)

print(dict_1)

output:

{'a': [1, 2], 'd': [4], 'c': [3]}
1

From the documentation for dictionaries:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.

1

Dictionary has unique keys. If you need the value of 'a' separately store the zipped data in a list or you can use list in values part of the dict and store the values as: {'a': [1,2],'c': [3], 'd': [4]}

1

As other answers have pointed out, dictionaries have unique keys, however, it is possible to create a structure to mimic the behavior you are looking for:

class NewDict:
   def __init__(self, *values):
       self.values = list(zip(*values))
   def __getitem__(self, key):
        return [b for a, b in sorted(self.values, key=lambda x:x[0]) if a == key]
   def __repr__(self):
       return "{}({})".format(self.__class__.__name__, "{"+', '.join("{}:{}".format(*i) for i in sorted(self.values, key=lambda x:x[0]))+"}")

list_one = ['a', 'a', 'c', 'd']
list_two = [1,2,3,4]
d = NewDict(list_one, list_two)
print(d['a'])
print(d)

Output:

[1, 2]
NewDict({a:1, a:2, c:3, d:4})
1
  • Wow. +1 for this awesome creativity.
    – RoadRunner
    Commented Dec 12, 2017 at 4:47
0

The keys in dictionary should be unique.

According to python documentation:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

link to the documentation

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.