How can I loop through the dictionary and access the first value in the dictionary? Note, I know this can be done without looping but in this case, I require looping so that is why I'm a little stuck.
For example: Suppose you have a dictionary d = {1: "Hello", 2: "Bye"}
. I want to loop through this dictionary and return "Hello"
. How can I do so?
I could do:
for first_value in d.values():
... # what do I do here?
CodePudding user response:
Break out of the loop after the first iteration:
for first_value in d.values():
break
print(first_value)
CodePudding user response:
I'm not entirely sure if I follow, but if you want to separate the first value from the rest, you can use the unpacking operator:
data = {1: "Hello", 2: "Bye"}
fst, *rest = data.values()
print(fst)
print(rest)
This outputs:
Hello
['Bye']