0

I am unsure if a dictionary can have values without keys, but am trying to learn more about dictionaries in python. I created a dictionary as follows:

dict={'Type': 'Electric_car', 'Make': 'Tesla', 'Model': 'S', 'Year': 2020, 'Price': 21000, '': 22.2}

I want to update the blank key in the dictionary to "Power":22.2
This is how I tried, which is obviously wrong.

for key, value in dict.items():
    if value==22.2:
        dict[key]=dict["Power"]

Is there any way to update the key by using the value?

Libin Thomas
  • 829
  • 9
  • 18
  • Maybe this is beside the point, but `22.2 != 22.22` – wjandrea Jun 06 '22 at 00:09
  • You might need this next: [How to avoid "RuntimeError: dictionary changed size during iteration" error?](https://stackoverflow.com/q/11941817/4518341) – wjandrea Jun 06 '22 at 00:11
  • Appreciate the suggestions. The examples show how to update to new key by popping the old key. I want to know if we can update the key only if its value is known. – Libin Thomas Jun 06 '22 at 00:24

3 Answers3

3

You could do something like d['Power'] = d.pop(''). Example:

>>> d = {'Type': 'Electric_car', 'Make': 'Tesla', 'Model': 'S', 'Year': 2020, 'Price': 21000, '': 22.2}
>>> d['Power'] = d.pop('')
>>> d
{'Type': 'Electric_car', 'Make': 'Tesla', 'Model': 'S', 'Year': 2020, 'Price': 21000, 'Power': 22.2}

However, it's fishy that you would be using the empty string as a key. You should try to not get yourself into that situation in the first place.

Dennis
  • 2,249
  • 6
  • 12
  • 1
    Where's the loop? OP wants to change the key based on the value, which requires a loop. – wjandrea Jun 06 '22 at 00:13
  • @wjandrea Yes! I want to know if we can change the key by its value, incase if I know just the value and not the key. Apologies, if it doesn't make sense. I want to understand the concept here. – Libin Thomas Jun 06 '22 at 00:15
  • 2
    You could do that with a loop like the example you showed (though as someone pointed out, there's a typo between 22.2 versus 22.22, and you probably need a `break` statement as well). However, it's generally a bad idea to put yourself in such a situation. Based on the example data, I would guess that 22.2 would never show up as the value of `Type` or `Year`, so you should format your data from the start in such a way that these don't have to be searched through. – Dennis Jun 06 '22 at 00:21
1

There's no way to "update" a key. The best you can do is re-insert with the new key, then delete the old key.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

This should work, though i'm sure it's not the most efficient route:

dict={'Type': 'Electric_car', 'Make': 'Tesla', 'Model': 'S', 'Year': 2020, 'Price': 21000, '': 22.2}

for key, value in list(dict.items()):
    if value == 22.2:
        dict["power"] = dict.pop(key)

Output:

{'Type': 'Electric_car', 'Make': 'Tesla', 'Model': 'S', 'Year': 2020, 'Price': 21000, 'power': 22.2}
Pwuurple
  • 352
  • 2
  • 11