Python: create dictionary using dict() with integer keys?

后端 未结 3 2003
深忆病人
深忆病人 2021-02-03 18:11

In Python, I see people creating dictionaries like this:

d = dict( one = 1, two = 2, three = 3 )

What if my keys are integers? When I try this:

3条回答
  •  难免孤独
    2021-02-03 18:28

    Yes, but not with that version of the constructor. You can do this:

    >>> dict([(1, 2), (3, 4)])
    {1: 2, 3: 4}
    

    There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

提交回复
热议问题