0

I have following dict and would like to get a key from it based upon list of values:

d = {
'Mot': [5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Dek': [0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Nas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Ost': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Suk': [0, 0, 0, 0, 0, 0, 0, 3156, 1320, 450, 0, 0, 0],
'Tas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 0, 0],
'Sat': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000]
}
    dz = [[5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

I tried to adopt get() method without any success (returning this error: unhashable type: 'list'; the same happened when I tried to have numpy's array instead returning: unhashable type: 'numpy.ndarray'):

tN= []
for index, element in enumerate(dz):
    tN.append(dict((v,k) for k,v in dict_res.items()).get(element))

Is there any way how to retrieve the values from dictionary like that?

New2coding
  • 715
  • 11
  • 23
  • 2
    You've put your dict on back-to-front. – wim Apr 13 '18 at 22:20
  • Possible duplicate of https://stackoverflow.com/questions/2568673/inverse-dictionary-lookup-in-python?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Artemis Apr 13 '18 at 22:21

2 Answers2

2

You can do something like this:

d = {
'Mot': [5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Dek': [0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Nas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Ost': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
'Suk': [0, 0, 0, 0, 0, 0, 0, 3156, 1320, 450, 0, 0, 0],
'Tas': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 250, 0, 0],
'Sat': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000]
}

dz = [[5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

keys = [key for elem in dz for key, value in d.items() if elem==value]
print(keys)

Output:

['Mot', 'Dek']

UPDATE:

Modified code so that you get the right order of keys. In case of:

dz = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000],
    [5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

the output is:

['Sat', 'Mot', 'Dek']
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
0

The solution posted above by Vasilis G. unfortunately reorders the returned values so in case of having:

dz = [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6551, 5000],
    [5250, 1085, 1085, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
      [0, 0, 0, 105, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

It outputs:

['Mot', 'Dek', 'Sat']

For cases one needs to know the true order of values in the list, this might be a better choice:

keys = []
for i in dz:
    keys.append(list(d.keys())[list(d.values()).index(i)])
#using list comprehension:
#keys = [list(d.keys())[list(d.values()).index(i)] for i in dz]

print(keys)

It prints:

['Sat', 'Mot', 'Dek']
New2coding
  • 715
  • 11
  • 23