How to create dictionary from two lists without lo

2020-03-24 06:42发布

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?

2条回答
贪生不怕死
2楼-- · 2020-03-24 07:10

you can use dict.setdefault():

In [20]: pin_list = ['in0', 'in1', 'in2', 'y']

In [21]: delvt_list = ['0.399', '0.1995', '0.1995', '0.399']

In [22]: dic={}

In [23]: for x,y in zip(pin_list,delvt_list):
    dic.setdefault(y,[]).append(x)
   ....:     

In [24]: dic
Out[24]: {'0.1995': ['in1', 'in2'], '0.399': ['in0', 'y']}

or if you want set based output:

In [29]: dic={}

In [30]: for x,y in zip(pin_list,delvt_list):
    dic.setdefault(y,set()).add(x)
   ....:     

In [31]: dic
Out[31]: {'0.1995': set(['in1', 'in2']), '0.399': set(['y', 'in0'])}

help() on dict.setdefault:

D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
查看更多
虎瘦雄心在
3楼-- · 2020-03-24 07:27

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).

查看更多
登录 后发表回答