I am wondering why when I use list(dictionary) it only returns keys and not their definitions into a list?
For example, I import a glossary with terms and definitions into a dictionary using CSV reader, then use the built in list() function to convert the dictionary to a list, and it only returns keys in the list.
It's not really an issue as it actually allows my program to work well, was just wondering is that just how it is supposed to behave or?
Many thanks for any help.
Do you mean by:
>>> d = {'a': [1, 2, 3], 'b': [4, 5, 6]}
>>> d.items()
dict_items([('a', [1, 2, 3]), ('b', [4, 5, 6])])
>>> list(d.items())
[('a', [1, 2, 3]), ('b', [4, 5, 6])]
>>>
Dictionary makes list(d) give it's keys, however list(d.values()) will give the values.
Also, in the documentation:
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary.
That tells you all.
why when I use list(dictionary) it only returns keys? ... just wondering is that just how it is supposed to behave or?
Because that's how it's designed to work.
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary.
Because (speculative):
The main operations on a dictionary are storing a value with some key and extracting the value given the key.
The values are not so consequential. Keys are unique identifiers. Values are mapped to keys. So dicts are indexed by key, iterated by key, etc. If you want a list of key/value tuple, then you have to call for that explicitly e.g., list(d.items()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With