Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 600
Jon A. Avatar asked Dec 01 '22 20:12

Jon A.


2 Answers

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

like image 192
Martijn Pieters Avatar answered Dec 17 '22 15:12

Martijn Pieters


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
like image 39
Ashwini Chaudhary Avatar answered Dec 17 '22 16:12

Ashwini Chaudhary