Ziu Ziu - 28 days ago 8
Python Question

Why would python dict's fromkeys method can accept a list as argument?

Based on Python2.7
Is that keys of dict must be immutable and hashable? And inside the list implementation, i find that

__hash__=None
, which means it is not hashable.

And we could use
fromkeys
to create dict like this:

d={}.fromkeys(('Alice', 'Bob'),3000)


Because tuple is immutable and hashable.

But i also find this is ok:

d={}.fromkeys(['Alice', 'Bob'],3000)


That really confused me. Why would
fromkeys
accept a list as argument?
Is there an implicit from list to tuple?
Thanks!

Answer

Read the statement very carefully, based on what you wrote:

keys of dict must be immutable

The fromkeys method takes an iterable. From the docstring:

Returns a new dict with keys from iterable and values equal to value.

You clearly provided two examples of this. What ends up happening is that the items in those iterables are strings which are immutable. It is those items that are going to be the keys of your dictionary.

Taking one of your examples, you can clearly see this from the output:

d={}.fromkeys(('Alice', 'Bob'),3000)

Output:

{'Alice': 3000, 'Bob': 3000}

If you had this, then you would get the expected error you think you should have gotten:

d={}.fromkeys((['Alice'], ['Bob']),3000)

Traceback (most recent call last):
  File "/Users/xxx/dev/rough/goo.py", line 31, in <module>
    d={}.fromkeys((['Alice'], ['Bob']),3000)
TypeError: unhashable type: 'list'