Python dictionary views

图片[1]-Python dictionary views - 拾光赋-拾光赋
图片[2]-Python dictionary views - 拾光赋-拾光赋 Christian Barra @christianbarra
图片[3]-Python dictionary views - 拾光赋-拾光赋 Did you know that “dict.keys()” returns a view that is a set-like object?
#Python 12:12 PM – 31 Jul 2018
图片[4]-Python dictionary views - 拾光赋-拾光赋
图片[5]-Python dictionary views - 拾光赋-拾光赋 2
5

Dictionary is one of the Python’s greatest features and using the keys(), items() and values() methods is really common.

first_dictionary = {"a": 1, "b": 2}
for key, value in first_dictionary.items():
    print(f"Key {key} with value {value}")

# Key a with value 1 # Key b with value 2 

But do you know which kind of object is returned?

They all return a special object, called view.

Why are views useful?

  • they provide a dynamic view on the underline object (you change the dictionary and the view will change as well)
  • the object returned by keys() and items() behaves like a set-like object (with items() when the pairs are hashable)

And being a set-like object means you can use the set operations.

Let’s consider an example, where we want to find the common keys between 2 dictionaries.

first_dictionary = {"a": 1, "b": 2}
second_dictionary = {"b": 2, "c": 3}

first_dictionary.keys() & second_dictionary.keys()
# {'b'} 

& is the intersection operator and returns the common elements between our dictionaries’ keys in this case.

What about the elements that are not in common?

first_dictionary = {"a": 1, "b": 2}
second_dictionary = {"b": 2, "c": 3}

first_dictionary.keys() ^ second_dictionary.keys()
# {'a', 'c'} 

This is called simmetric difference.

One thing that you cannot do is change the dictionary while iterating over the view object.

for key, value in first_dictionary.items():
    del first_dictionary[key]

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: dictionary changed size during iteration

原文链接:Python dictionary views

© 版权声明
THE END
喜欢就支持一下吧
点赞9 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容