How to extract dictionary single key-value pair in variables

后端 未结 10 1667
别那么骄傲
别那么骄傲 2020-12-08 06:33

I have only a single key-value pair in a dictionary. I want to assign key to one variable and it\'s value to another variable. I have tried with below ways but I am getting

相关标签:
10条回答
  • 2020-12-08 07:03

    Add another level, with a tuple (just the comma):

    (k, v), = d.items()
    

    or with a list:

    [(k, v)] = d.items()
    

    or pick out the first element:

    k, v = d.items()[0]
    

    The first two have the added advantage that they throw an exception if your dictionary has more than one key, and both work on Python 3 while the latter would have to be spelled as k, v = next(iter(d.items())) to work.

    Demo:

    >>> d = {'foo': 'bar'}
    >>> (k, v), = d.items()
    >>> k, v
    ('foo', 'bar')
    >>> [(k, v)] = d.items()
    >>> k, v
    ('foo', 'bar')
    >>> k, v = d.items()[0]
    >>> k, v
    ('foo', 'bar')
    >>> k, v = next(iter(d.items()))  # Python 2 & 3 compatible
    >>> k, v
    ('foo', 'bar')
    
    0 讨论(0)
  • 2020-12-08 07:04

    This is best if you have many items in the dictionary, since it doesn't actually create a list but yields just one key-value pair.

    k, v = next(d.iteritems())
    

    Of course, if you have more than one item in the dictionary, there's no way to know which one you'll get out.

    0 讨论(0)
  • 2020-12-08 07:12

    You have a list. You must index the list in order to access the elements.

    (k,v) = d.items()[0]
    
    0 讨论(0)
  • 2020-12-08 07:15
    key = list(foo.keys())[0]
    value = foo[key]
    
    0 讨论(0)
  • 2020-12-08 07:16

    Use the .popitem() method.

    k, v = d.popitem()
    
    0 讨论(0)
  • 2020-12-08 07:17

    items() returns a list of tuples so:

    (k,v) = d.items()[0]
    
    0 讨论(0)
提交回复
热议问题