Return the first key in Dictionary - Python 3
in python3 data.keys()
returns a dict_keys
object, so, in general, apply list on it to be able to index/slice it:
data = {"Key1" : "Value1", "Key2" : "Value2"}
print(data.keys())
# output >>> dict_keys(['Key1', 'Key2'])
print(list(data.keys())[1])
# output >>> Key2
print(list(data.values())[1])
# output >>> Value2
For your specific case, you need to convert the dictionary to an ordered one to conserve the order and get the first element as follows:
from collections import OrderedDict
data = {"Key1" : "Value1", "Key2" : "Value2"}
data = OrderedDict(data)
print(data)
# output >>> OrderedDict([('Key1', 'Value1'), ('Key2', 'Value2')])
print(list(data.keys())[0])
# output >>> Key1
Edit:
Based on comments from @Mseifert (thanks), preserving the order after conversion from the unordered dictionary to the ordered one is only an implementation detail that works in python3.6 and we cannot rely on, here's the discussion Mseifert shared:
- Dictionaries are ordered in Python 3.6+
So the correct way to do what you want is to explicitly define the order
from collections import OrderedDict
data = OrderedDict([('Key1', 'Value1'), ('Key2', 'Value2')])
print(list(data.keys())[0])
Shortest:
mydict = {"Key1" : "Value1", "Key2" : "Value2"}
print( next(iter(mydict)) ) # 'Key1'
For both the key and value:
print( next(iter( mydict.items() )) ) # ('Key1', 'Value1')