Converting the keys of a dictionary from numeric to string
Peter Otten
__peter__ at web.de
Thu Oct 20 04:33:20 EDT 2016
Peter Otten wrote:
> Paul Rubin wrote:
>
>> Peter Otten <__peter__ at web.de> writes:
>>> assert len(keydict) == len(mydict)
>>
>> assert set(keydict) == set(mydict)
>
> The weaker check is O(1), and, combined with the succeeding for loop,
> implies the above.
Sorry, I have to take that back:
Python 3.6.0b1+ (3.6:5c92f9e0a8b1, Sep 13 2016, 14:44:51)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> keydict = { 1: "Joseph", "Joseph": "Michael", 3: "John" }
>>> mydict = { 1: 1000, 2: 2000, 3: 3000 }
>>> assert len(keydict) == len(mydict)
>>> assert set(keydict) == set(mydict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>> for k, v in keydict.items():
... mydict[v] = mydict.pop(k)
...
>>> print(mydict)
{2: 2000, 'Michael': 1000, 'John': 3000}
More information about the Python-list
mailing list