print the value of the first key in dictionary using key() method

Viewed 32
pyDic= {'1': 'MEMBER1', '2': 'MEMBER2' ,'3': 'MEMBER3', '4': 'MEMBER4' , '5': 'MEMBER5'}
print(pyDic.keys(1))
1 Answers

To get the first value from a dictionary you can do this:

pyDic= {'1': 'MEMBER1', '2': 'MEMBER2' ,'3': 'MEMBER3', '4': 'MEMBER4' , '5': 'MEMBER5'}

print(next(iter(pyDic.values())))

The dictionary function values() returns a reference to a dict_values class. This can be converted to an iterator with iter() then call next() on the iterator to get the first value.

Another option is to create a list from the dict_values class and then take the 0th element as follows:

print(list(pyDic.values())[0])

You can also unpack as follows:

value, *_ = pyDic.values()
print(value)

Output:

MEMBER1
Related