![]() |
Dictionary using variables as a keys - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Dictionary using variables as a keys (/thread-5466.html) |
Dictionary using variables as a keys - andresgt - Oct-05-2017 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 RE: Dictionary using variables as a keys - nilamo - Oct-05-2017 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} >>> RE: Dictionary using variables as a keys - miltmobley - Oct-09-2017 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} RE: Dictionary using variables as a keys - nilamo - Oct-10-2017 (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? RE: Dictionary using variables as a keys - buran - Oct-10-2017 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 Note that in case there are multiple min values in list2, the result will be dict with multiple elements
|