1

Newbie question in dictionaries.

I'm trying to replace keys with values without using iteritems like I've seen in some answers here.

I have 2 dictionaries. One with stuff in it and an empty one. I'd like to keep the first one as is, but print out the second one with the the keys and values replaced from the first one.

So for example:

d1 = {1:"hello", 2 : 10, 3 : 100.0}

The print of d2 will be "hello":1, 10:2, 100.0:3

This is my try:

d1 = {1:"hello", 2 : 10, 3 : 100.0}
d2 = {}
for k in d1:
    d2[d1[k]] == d2[k]
print(d2)

I'm not quite sure where I'm wrong.

Daniel
  • 621
  • 5
  • 22

3 Answers3

3

try this code:

 d1 = {1:"hello", 2 : 10, 3 : 100.0} 

d2 = dict([(value, key) for key, value in d1.items()]) 

for i in d2: 
    print(i, " :  ", d2[i]) 
2

Your code need slight altering to get it to work as intended:

d1 = {1:"hello", 2 : 10, 3 : 100.0}
d2 = {}
for k in d1.keys():
    d2[d1[k]] = k
print(d2) # {'hello': 1, 10: 2, 100.0: 3}

Keep in mind however that values in dict might repeat, while keys can not (must be unique), so if any value will appear more than once in d1, after such operation you will have fewer elements in d2.

Daweo
  • 31,313
  • 3
  • 12
  • 25
1

You can also use .items() :-

d1 = {1:"hello", 2 : 10, 3 : 100.0}
d2 = {}
for key, value in d1.items():
    d2[value] = key
print(d2)

I hope it may help you.

Rahul charan
  • 765
  • 7
  • 15