Dictionary get value without knowing the key

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"

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.