Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usage of "dict_value" and "dict_key" in python3

dict = {'a':1, 'b':2}

dict.keys gives dict_keys(['a', 'b'])

dict.values gives dict_values([1, 2]).

Can someone give examples how dict_keys and dict_values come handy? Why dictionary returns these types instead of just returning a list?

I often do list(dict.keys) and list(dict.values), converting into a list to loop over.

like image 419
Lisa Avatar asked Mar 12 '19 15:03

Lisa


2 Answers

Perhaps you have the question the other way around: why should these methods return a list?

As the comments point out, if these methods had to return lists, then this list would have to be made first. By contrast, you can iterate over the dict_keys and dict_values objects without creating an entire big list. (You say you often cast these objects to lists, to loop over them. You don't need to do this: you can loop over the objects directly, as in for value in my_dict.values().)

If you really need a list (which is usually not the case, mind you), then consider that it's better to be explicit, and create a list yourself: x = list(my_dict.keys()).

like image 95
acdr Avatar answered Oct 27 '22 10:10

acdr


Doing list(dict.keys() takes memory for the whole created list:

import sys

d = {i: i for i in range(10000000)}
view = d.keys()
lst = list(d.keys())

print(sys.getsizeof(view))  # 48
print(sys.getsizeof(lst))  # 90000112

Creating only dict.keys() and iterating over it doesn't take so much memory.

dict.keys(), dict.values() and dict.items() return dictionary view objects. keys and items views are set-like objects, so set operations are available for them, example from this doc:

>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'}
{'juice', 'sausage', 'bacon', 'spam'}

Also you can create not only a list from these views:

t = tuple(keys)
like image 41
sanyassh Avatar answered Oct 27 '22 08:10

sanyassh