简体   繁体   中英

Dictionary get value without knowing the key

In python if I have a dictionary which has a single key value pair and if I don't know what the key might be, how can I get the value?

(and if I have a dict with more than 1 key, value pair, how can I return any one of the values without knowing any of the keys?)

You just have to use dict.values() .

This will return a list containing all the values of your dictionary, without having to specify any key.

You may also be interested in:

  • .keys() : return a list containing the keys
  • .items() : return a list of tuples (key, value)

Note that in Python 3, returned value is not actually proper list but view object .

Further to Delgan's excellent answer, here is an example for Python 3 that demonstrates how to use the view object:

In Python 3 you can print the values, without knowing/using the keys, thus:

for item in my_dict:
    print( list( item.values() )[0] )

Example:

 cars = {'Toyota':['Camry','Turcel','Tundra','Tacoma'],'Ford':['Mustang','Capri','OrRepairDaily'],'Chev':['Malibu','Corvette']} vals = list( cars.values() ) keyz = list( cars.keys() ) cnt = 0 for val in vals: print('[_' + keyz[cnt] + '_]') if len(val)>1: for part in val: print(part) else: print( val[0] ) cnt += 1 OUTPUT: [_Toyota_] Camry Turcel Tundra Tacoma [_Ford_] Mustang Capri OrRepairDaily [_Chev_] Malibu Corvette

That Py3 docs reference again:

https://docs.python.org/3.5/library/stdtypes.html#dict-views

Other solution, using popitem and unpacking:

d = {"unknow_key": "value"}
_, v = d.popitem()
assert v == "value"

Two more ways:

>>> d = {'k': 'v'}

>>> next(iter(d.values()))
'v'

>>> v, = d.values()
>>> v
'v'

One more way: looping with for/in through a dictionary we get the key(s) of the key-value pair(s), and with that, we get the value of the value.

>>>my_dict = {'a' : 25}
>>>for key in my_dict:
       print(my_dict[key])
25

>>> my_other_dict = {'b': 33, 'c': 44}
>>> for key in my_other_dict:
        print(my_other_dict[key])
33
44

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM