0

Which is the proper way to write this code

  getter = {
        0 : "value_1",
        1 : "value_1",
        2 : "value_1",
        3 : "value_2",
        4:  "value_3"
    }

and get the values as

   for k in keys:
    value = getter[ keys ]
    #.. then, you do other stuffs with the picked value

I want to avoid repeating "value_1"rows for different keys on dictionary declaration.

f_s
  • 113
  • 10
  • To access both key and values in python you can use `for k,v in getter.items():` – Sabsa Jul 07 '22 at 09:20
  • Does this answer your question? [remove duplicates values in a dictionary python](https://stackoverflow.com/questions/27218704/remove-duplicates-values-in-a-dictionary-python) – Carlos Horn Jul 07 '22 at 10:56

3 Answers3

0
getter = {
        0 : "value_1",
        1 : "value_1",
        2 : "value_1",
        3 : "value_2",
        4:  "value_3"
    }
temp={val:key for key,val in getter.items()}
res={val:key for key, val in temp.items()}  # {2: 'value_1', 3: 'value_2', 4: 'value_3'}

You can remove duplicates from a dictionary like this.

But if you don't have to skip any key of getter, you can save and check the key after do something.

processed_value = list()
for key, value in getter.items():
    if value in processed_value:
        continue
    processed_value.append(value)
    #.. then, you do other stuffs with the picked value
Lazyer
  • 917
  • 1
  • 6
  • 16
0

if you want specific keys then you may have to loop through the dictionary and save the keys you want with values you are trying to find, if you dont bother about what keys you want then @Lazyer answer will help you

Gopi Krishna
  • 108
  • 2
  • 16
0

Just for fun, in a single statement... Using the fact that

  • a dictionary can be constructed out of tuples and
  • removing extra values by making a new dictionary with keys the original value (need a swap -> reversed)
  • swap back
getter_new = dict(zip(*reversed(list(zip(*dict(zip(*reversed(list(zip(*getter.items()))))).items())))))

print(getter_new)
#{2: 'value_1', 3: 'value_2', 4: 'value_3'}

Notice that the last key with a repeated value will be the "dominant" one.

cards
  • 3,936
  • 1
  • 7
  • 25