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

后端 未结 3 1991
深忆病人
深忆病人 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."

    0 讨论(0)
  • 2021-02-03 18:31
    a = dict(one=1, two=2, three=3)
    

    Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

    0 讨论(0)
  • 2021-02-03 18:41

    There are also these 'ways':

    >>> dict.fromkeys(range(1, 4))
    {1: None, 2: None, 3: None}
    >>> dict(zip(range(1, 4), range(1, 4)))
    {1: 1, 2: 2, 3: 3}
    
    0 讨论(0)
提交回复
热议问题