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?
you can use
dict.setdefault()
:or if you want
set
based output:help()
ondict.setdefault
:Use
collections.defaultdict
: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: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).