Python Forum

Full Version: Dictionary using variables as a keys
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Im trying to create a dicctionary using two lists (one as a key and the other one as a value) like this:

list1 = ['A4', 'A9', 'A2'] # keys
list2 = [27.8, 7.1, 68.04] # values

Diccionary : {'A4': [27.8], 'A9': [7.1], 'A2': [68.04]}

Finally I need to sort by value and take the minimum value and key:

In this case: {'A9':[7.1]}


Thanks in advance
zip them, to create key-value pairs.
>>> keys = ['A4', 'A9', 'A2']
>>> values = [27.8, 7.1, 68.04]
>>> list(zip(keys, values))
[('A4', 27.8), ('A9', 7.1), ('A2', 68.04)]
>>> dict(zip(keys, values))
{'A9': 7.1, 'A4': 27.8, 'A2': 68.04}
>>>
The solution above uses a dict, but does not sort on the values.
You can say:

>>> a=[1,2,3]
>>> b=[6,5,4]
>>> c=zip(a,b)
>>> c
[(1, 6), (2, 5), (3, 4)]
>>> d=sorted(c, key=lambda x: x[1]) # sort on value element
>>> d
[(3, 4), (2, 5), (1, 6)]
>>> e=dict(d)
>>> e
{1: 6, 2: 5, 3: 4}
(Oct-09-2017, 10:33 PM)miltmobley Wrote: [ -> ]
>>> d
[(3, 4), (2, 5), (1, 6)]
>>> e=dict(d)
>>> e
{1: 6, 2: 5, 3: 4}

Ok, but that's not sorted by value, either.  And since dictionaries only maintain order in some versions of python, for some implementations of python, shouldn't you just assume all dictionaries are just unordered?
list1 = ['A4', 'A9', 'A2'] # keys
list2 = [27.8, 7.1, 68.04] # values
d = {k:v for k,v in zip(list1, list2) if v==min(list2)}
print d
Output:
{'A9': 7.1}
Note that in case there are multiple min values in list2, the result will be dict with multiple elements