Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

python - Creating a dictionary from 2 lists with duplicate keys

Though I have seen versions of my issue whereby a dictionary was created from two lists (one list with the keys, and the other with the corresponding values), I want to create a dictionary from a list (containing the keys), and 'lists of list' (containing the corresponding values).

An example of my code is:

#-Creating python dictionary from a list and lists of lists:
keys = [18, 34, 30, 30, 18]
values = [[7,8,9],[4,5,6],[1,2,3],[10,11,12],[13,14,15]]
print "This is example dictionary: "
print dictionary

The result I expect to get is:

{18:[7,8,9],34:[4,5,6],30:[1,2,3],30:[10,11,12],18:[13,14,15]}

I do not need the repeated keys (30, 18) to be paired up with their respective values.

Instead, I keep getting the following result:

{18: [13, 14, 15], 34: [4, 5, 6], 30: [10, 11, 12]}

This result is missing two of the elements from my expected list.

I am hoping to have some help from this forum.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As already mentioned, your desired output is not possible as dictionary keys must be unique.

Below are 2 alternatives if you do not want to lose data.

List of tuples

res = [(i, j) for i, j in zip(keys, values)]

# [(18, [7, 8, 9]),
#  (34, [4, 5, 6]),
#  (30, [1, 2, 3]),
#  (30, [10, 11, 12]),
#  (18, [13, 14, 15])]

Dictionary of lists

from collections import defaultdict

res = defaultdict(list)

for i, j in zip(keys, values):
    res[i].append(j)

# defaultdict(list,
#             {18: [[7, 8, 9], [13, 14, 15]],
#              30: [[1, 2, 3], [10, 11, 12]],
#              34: [[4, 5, 6]]})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...