- Simplest/most straightforward:
d = {"A":1,"B":2,"C":3}
inv = {}
for k in d.keys():
inv[d[k]] = k
- Alternative: use
d.items()
, iterate over tuples
d = {"A":1,"B":2,"C":3}
inv = {}
for a,b in d.items():
inv[b] = a
- Iterate over tuples, build up a reversed list, pass it to
dict()
d = {"A":1,"B":2,"C":3}
invlist = []
for a,b in d.items():
invlist.append([b,a])
inv = dict(invlist)
- Same thing with a list comprehension:
d = {"A":1,"B":2,"C":3}
dict([[b,a] for a,b in d.items()])
- Or using
zip()
:
d = {"A":1,"B":2,"C":3}
dict(zip(d.values(),d.keys()))