Python dictionary creation error

前端 未结 1 580
傲寒
傲寒 2021-01-19 04:56

I am trying to create a Python dictionary from a stored list. This first method works

>>> myList = []
>>> myList.append(\'Prop1\')
>>&         


        
相关标签:
1条回答
  • 2021-01-19 05:17

    You're doing it wrong.

    The dict() constructor doesn't take a list of items (much less a list containing a single list of items), it takes an iterable of 2-element iterables. So if you changed your code to be:

    myList = []
    myList.append(["mykey1", "myvalue1"])
    myList.append(["mykey2", "myvalue2"])
    myDict = dict(myList)
    

    Then you would get what you expect:

    >>> myDict
    {'mykey2': 'myvalue2', 'mykey1': 'myvalue1'}
    

    The reason that this works:

    myDict = dict([['prop1', 'prop2']])
    {'prop1': 'prop2'}
    

    Is because it's interpreting it as a list which contains one element which is a list which contains two elements.

    Essentially, the dict constructor takes its first argument and executes code similar to this:

    for key, value in myList:
        print key, "=", value
    
    0 讨论(0)
提交回复
热议问题