Home > Mobile >  Can't find the first element of a dict
Can't find the first element of a dict

Time:10-25

I want to get the first element of a dict, "names(1)" doesn't work.

names = {"John":20, "Marc":22, "Dwayne":23}
print(names(1))

CodePudding user response:

First use iter to get an iterator of keys out of the dict (this is based on insertion order as of python 3.6 ). Then use next() to get the first item (first key) from that iterator:

names = {"John": 20, "Marc": 22, "Dwayne": 23}
print(next(iter(names)))

Result:

John  # first according to insertion order

CodePudding user response:

You can get the first element of it (only in versions with ordered dictionaries) with

print(next(iter(names)))

In names = {"John":20, "Marc":22, "Dwayne":23} outuput is "John"

  • Related