0

I have two dictionaries and my objective was to replace the keys in first_dict, with the values in second_dict.

I got the code working, but largely through trial and error, so would like some help understanding and translate exactly what is going on here in Python.

first_dict={"FirstName": "Jeff", "Town": "Birmingham"}
second_dict={"FirstName": "c1", "Town": "c2"}
new_dict = {second_dict[k]: v for k, v in first_dict.items()}

This gives me what I want, a new dict as follows:

{'c1': 'Jeff', 'c2': 'Birmingham'}

How is this working?

  • "new_dict" creates a new dictionary
  • so "in first_dict.items()", i.e. for each key-value paid in "first_dict":
  • the value in the new_dict is the value from "row"
  • the key in the new_dict is the value from the second_dict

How does "second_dict[k]" do this? it seems like it is doing some sort of a lookup to match between the keys of first_dict and second_dict? Is this right, and if so, how does it work?

alexei7
  • 182
  • 1
  • 3
  • 11

1 Answers1

1

Python dictionaries are implemented using hash tables. It is basically an array. To access the array we need indices. The indices are obtained using a hash function on the keys. Hash function tries to distribute the key evenly (property of any hash function - hash functions hate collisions).

When you are creating the last dictionary, it just reads the k and v from the other dictionary and then the value v's become the key of the new dictionary. So yes, the hash function finds out the hashed values and then in that index put the correct value (which is k from other dictionary for you).

Note: How a hashtable handles collision is a separate topic in itself. There are several ways of handling this. One of them is open addressing scheme. You can look that up for further details.

user2736738
  • 30,591
  • 5
  • 42
  • 56