+ 4
Dictionary and tuples.
Why does a dictionary return a tuple? https://code.sololearn.com/c101PfwH7gO1/?ref=app
6 Respostas
+ 5
I figured it does that because if it returned a list of items they can be changed. Theres a lot of ways to change a dictionary but using .items() isnt one of them. Its more there just to show you everything and make it easier to display. While being a sort of "protecter" of data since tuples are immutable theres no mixing or changing the data.
+ 6
You can also loop through keys or values separately
person.keys()
person.values()
And it is also common to unpack the key-value pairs in two variables:
for key, value in person.items()
+ 4
dictionarys return tuples when you call the .items() method on them. Example:
games = {'cod':60, 'skyrim':50, 'darksouls':100}
for k,v in games.items():
print(k+'is'+v+'dollars.')
cod is 60 dollars.
skyrim is 50 dollars.
darksouls is 100 dollars.
+ 4
You said it yourself: key-value PAIR.
A tuple is exactly that: an immutable group of data, in this case a pair.
You can observe a similar thing when you use zip() function over two iterables, it combines them pair-wise and returns a sequence of tuples.
+ 4
Slick and Tibor Santa that's some answer I was looking for, a good reason.
Thanks to both of you.
+ 3
Hi Tibor Santa and Slick I know that we can iterate over keys and values separately as well and it returns just what has been asked for. But my question is why do they return a tuple when we return both key-value pair combined.
I thought there must be some reason behind it. Anyways thanks guys.