Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - How to map multiple lists to one dictionary?

I used this code:

dictionary = dict(zip(list1, list2))

in order to map two lists in a dictionary. Where:

list1 = ('a','b','c')
list2 = ('1','2','3')

The dictionary equals to:

{'a': 1, 'c': 3, 'b': 2}

Is there a way to add a third list:

list3 = ('4','5','6')

so that the dictionary will equal to:

{'a': [1,4], 'c': [3,5], 'b': [2,6]}

This third list has to be added so that it follows the existing mapping.

The idea is to make this work iteratively in a for loop and several dozens of values to the correctly mapped keyword. Is something like this possible?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)
dict((z[0], list(z[1:])) for z in zip(list1, list2, list3))

will work. Or, if you prefer the slightly nicer dictionary comprehension syntax:

{z[0]: list(z[1:]) for z in zip(list1, list2, list3)}

This scales up to to an arbitrary number of lists easily:

list_of_lists = [list1, list2, list3, ...]
{z[0]: list(z[1:]) for z in zip(*list_of_lists)} 

And if you want to convert the type to make sure that the value lists contain all integers:

def to_int(iterable):
    return [int(x) for x in iterable]

{z[0]: to_int(z[1:]) for z in zip(*list_of_lists)}

Of course, you could do that in one line, but I'd rather not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...