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
394 views
in Technique[技术] by (71.8m points)

python - How to create dictionary from two lists without losing duplicate values?

I have two lists:

pin_list = ['in0', 'in1', 'in2', 'y']
delvt_list = ['0.399', '0.1995', '0.1995', '0.399']

I use the code: temp = dict(zip(delvt_list,pin_list)) but I get the following:

temp = {'0.1995': 'in2', '0.399': 'y'}

What Python code do I need to write to get:

temp =  {'0.1995': {'in2', 'in1'}, '0.399': {'y', 'in0'}}

or

temp =  {'0.1995': ['in2', 'in1'], '0.399': ['y', 'in0']}

As an additional question, if I want to use the values in temp to search a line that I am reading in would it be easier with sets or lists?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use collections.defaultdict:

temp = defaultdict(set)

for delvt, pin in zip(delvt_list, pin_list):
    temp[delvt].add(pin)

This creates a defaultdict where the default value is a set, then loop and add the values for each key.

If you wanted a list instead, simply change the default type and how you add values to match the list interface:

temp = defaultdict(list)

for delvt, pin in zip(delvt_list, pin_list):
    temp[delvt].append(pin)

Sets are a better idea when you want to test for membership (something in aset); such tests take constant time, vs. linear time for a list (so set membership tests take a fixed amount of time independent of the size of the set, while for lists it takes more time, proportional to the number of elements in the list).


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

...