S
S
Sergey2018-10-03 18:00:49
Python
Sergey, 2018-10-03 18:00:49

How to get only the first key from the dictionary?

car = {
    'MAN': '777',
    'AUDI': '888',
    'VOLVO': '999',
    'BMW': '000',
}

for key in car:
    print(f"{key}")

So it displays all the keys that are, but only "MAN" is needed.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2018-10-03
@Serjdragonknight

first_key = list(car.keys())[0]
or
first_key = next(iter(car.keys()))

A
Alexander Semenenko, 2018-10-03
@semenenko88

print(car.get('MAN'))

D
Dmitry, 2018-10-03
@superD

And no one wrote about the fact that Python < 3.6 does not guarantee the order of keys in a dictionary (hash table), like many other languages:
https://stackoverflow.com/questions/5629023/key-or...
If important so that the first key is the one that was specified first when defining the dictionary, you can use OrderedDict.
In Python >= 3.6 this problem is no longer there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question