2

I have dictionary dict like this, with tuples as keys:

 dict = { (1, 1): 10, (2,1): 12} 

and tried to access it like this :

new_dict = {}
for key, value in dict: 
    new_dict["A"] = key[0]
    new_dict["B"] = key[1]
    new_dict["C"] = value

But it fails, since key does not seem to resolves to a tuple. What is the correct way?

nucsit026
  • 652
  • 7
  • 16
Bart Jonk
  • 365
  • 3
  • 14

1 Answers1

5

To iterate over key value pairs, use the .items() method of the dict.

Also, give the dictionary a name like my_dict to avoid overwriting the builtin dict.

new_dict = {}
for key, value in my_dict.items(): 
    new_dict["A"] = key[0]
    new_dict["B"] = key[1]
    new_dict["C"] = value
ac24
  • 5,325
  • 1
  • 16
  • 31