4

given a dictionary:

 d = {'name': 'Luke', 'age': 43, 'friend': 'Joe'}

i'm trying to build a function that will change it so that the new dictionary will be:

d = {'Luke': 'name', 43: 'age', 'Joe':'friend'}

in other words the key will become the values and the values will become the keys. also the id of the dictionary wont change.

i tried this code:

dict(map(reversed, d.items()))

i'm using python 3.x any help will be appreciated.

Guy L
  • 43
  • 1
  • 1
  • 4
  • 2
    Since dictionaries [by definition](https://docs.python.org/3.6/tutorial/datastructures.html#dictionaries) have no order, what do you mean by "the order needs to be the same"? – Rory Daulton Apr 16 '17 at 11:14
  • @RoryDaulton , lets say d = {'Luke': 'name', 'Joe':'friend', 43: 'age'} wont be a good output – Guy L Apr 16 '17 at 11:18
  • 1
    Invert would be the term, I guess as the sample shows a dict constructed somehow like: `inverted = dict((v, k) for k, v in d.items())` (in that case the values also have to be unique) - reverse is about ordering. PS: In python 3.6.1 the dict remains the insert order ;-) i.e. `{'Luke': 'name', 43: 'age', 'Joe': 'friend'}`result from above ... – Dilettant Apr 16 '17 at 11:19
  • 1
    What are you really trying to achieve here? Why do you have to modify the dictionary in-place? What if there are two keys with the same value? – jonrsharpe Apr 16 '17 at 11:19
  • So short hints: a) Think inverted (not reversed), b) ensure it is invertable 3) use python 3.6.1 or an ordered dict in lower versions, done. – Dilettant Apr 16 '17 at 11:21
  • As Rory said, and as the documentation states, there's *no order* in dictionaries. So, the order in which you write the keys and values when you create it doesn't get remembered, and the order in which they appear when you print it is about random. – Thierry Lathuille Apr 16 '17 at 11:22

3 Answers3

4

If you want to invert the dictionary without changing its id you need to build a temporary dictionary, clear the old one, and update it. Here's how to do that using a dictionary comprehension.

d = {'name': 'Luke', 'age': 43, 'friend': 'Joe'}
print(d, id(d))

# Invert d
t = {v: k for k, v in d.items()}

# Copy t to d
d.clear()
d.update(t)
# Remove t
del t
print(d, id(d))

output

{'name': 'Luke', 'age': 43, 'friend': 'Joe'} 3072452564
{'Luke': 'name', 43: 'age', 'Joe': 'friend'} 3072452564

Tested using Python 3.6, which preserves the order of plain dictionaries. It's not strictly necessary to del t, but you might as well if you don't need it. Of course, if you're doing this inside a function t will get garbage collected as soon as it goes out of scope anyway.

You need to be careful when doing this: all the values must be immutable objects, and any duplicated values will get clobbered.

Also, while it's perfectly legal, some people consider it bad style to have mixed types for your dictionary keys. And if you want to create a sorted list of the dict's items you won't be able to do that easily in Python 3 if the keys are of mixed types. You can't sort keys of mixed types because Python 3 doesn't permit you to compare objects of mixed type.

PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

Try this: dict([(v, k) for k, v in d.iteritems()])

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
HanaKenzou
  • 41
  • 1
  • 5
  • 1
    Welcome to Stack Overflow! While this code snippet may solve the question, [including an explanation](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. – jmattheis Apr 16 '17 at 12:13
  • Ok. Thanks for letting me know – HanaKenzou Apr 17 '17 at 22:39
0

Using a dictionary comprehension, here's your inverted dictionary:

rev_dict = {v: k for k, v in d.items()}

If you're interested in ordered dictionaries in Python (as built-in dictionaries are inherently unordered), I would encourage you to check out collections.OrderedDict.

blacksite
  • 12,086
  • 10
  • 64
  • 109