Dictionary get value without knowing the key

Question:

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?)

Asked By: Yunti

||

Answers:

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.

Answered By: Delgan

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

Answered By: cssyphus

Other solution, using popitem and unpacking:

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

Two more ways:

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

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

>>> v, = d.values()
>>> v
'v'
Answered By: superb rain

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
Answered By: Stefano
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.