Home  >  Article  >  Backend Development  >  How to use lists of Python dictionaries

How to use lists of Python dictionaries

php中世界最好的语言
php中世界最好的语言Original
2018-04-09 17:54:172121browse

This time I will bring you Pythonhow to use the dictionary list, what are the notes when using the Python dictionary list, the following is a practical case, let's take a look.

1. Use the in keyword to check whether the key exists

There is a development philosophy in the Zen of Python:

There should be one-- and preferably only one --obvious way to do it.

Try to find one, preferably only one obvious way to do it. In Python2, you can use the has_key method to determine whether a key exists in the dictionary. Another way is to use the in keyword. However, it is strongly recommended to use the latter, because in is processed faster. Another reason is that the has_key method was removed in Python3. If you want to be compatible with both py2 and py3 versions of the code, using in is the best choice.

bad
d = {'name': 'python'}
if d.has_key('name'):
  pass
good
if 'name' in d:
  pass

2. Use get to get the value in the dictionary

Regarding getting the value in the dictionary, a simple way is to use d[x] to access the element. However, in this case, a KeyError error will be reported when the key does not exist. Of course, you can first use the in operation to check whether the key is in the dictionary and then obtain it, but this method does not comply with what is said in the Zen of Python:

Simple is better than complex.
Flat is better than nested.

Good code should be simple and easy to understand, and a flat code structure is more readable. We can use the get method instead of if... else

bad
d = {'name': 'python'}
if 'name' in d:
  print(d['hello'])
else:
  print('default')
good
print(d.get("name", "default"))

3. Use setdefault to set default values ​​for keys that do not exist in the dictionary

data = [
    ("animal", "bear"),
    ("animal", "duck"),
    ("plant", "cactus"),
    ("vehicle", "speed boat"),
    ("vehicle", "school bus")
  ]

Doing classification When doing statistics, you want to classify the same type of data into a certain type in the dictionary. For example, in the above code, you can reassemble the same type of things in the form of a list to get a new dictionary.

groups = {}
>>> 
{'plant': ['cactus'], 
 'animal': ['bear', 'duck'], 
 'vehicle': ['speed boat', 'school bus']}

The common way is First determine whether the key already exists. If it does not exist, initialize it with the list object before performing subsequent operations. A better way is to use the setdefault method in the dictionary.

bad
for (key, value) in data:
  if key in groups:
    groups[key].append(value)
  else:
    groups[key] = [value]
good
groups = {}
for (key, value) in data:
  groups.setdefault(key, []).append(value)

The function of setdefault is:

If the key exists in the dictionary, then the corresponding value is returned directly, which is equivalent to the get method

If the key does not exist in the dictionary, The second parameter in setdefault will be used as the value of the key, and then the value will be returned.

4. Initialize the dictionary object with defaultdict

If you do not want d[x] to report an error when x does not exist, in addition to using the get method when obtaining elements, Another way is to use defaultdict in the collections module and specify a function when initializing the dictionary. In fact, defaultdict is a subclass of dict.

from collections import defaultdict
groups = defaultdict(list)
for (key, value) in data:
  groups[key].append(value)

When key does not exist in the dictionary, the list function will be called and return an empty list to assign to d[key]. In this way, you don’t have to worry about calling d[k] and reporting an error.

5. Use fromkeys to convert the list into a dictionary

keys = {'a', 'e', 'i', 'o', 'u' }
value = []
d = dict.fromkeys(keys, value)
print(d)
>>>
{'i': [], 'u': [], 'e': [], 
 'a': [], 'o': []}

6. Use a dictionary to implement switch ... case statement

There is no switch...case statement in Python. Uncle Turtle, the father of Python, said that this syntax did not exist in the past, does not exist now, and will not exist in the future. Because Python's concise syntax can be implemented using if ... elif. If there are too many branch judgments, you can also use a dictionary instead.

if arg == 0:
  return 'zero'
elif arg == 1:
  return 'one'
elif arg == 2:
  return "two"
else:
  return "nothing"
good
data = {
  0: "zero",
  1: "one",
  2: "two",
}
data.get(arg, "nothing")

7. Use iteritems to iterate elements in the dictionary

Python provides several ways to iterate elements in the dictionary. The first is to use the items method:

d = {
  0: "zero",
  1: "one",
  2: "two",
}
for k, v in d.items():
  print(k, v)

items method returns a list object composed of (key, value). The disadvantage of this method is that when iterating a very large dictionary, the memory will be doubled in an instant, because the list object will load all elements into Memory, a better way is to use iteritems

for k, v in d.iteritems():
  print(k, v)

iteritems returns an iterator object. The iterator object has the characteristics of lazy loading. The value is only generated when it is really needed. This method does not Additional memory is required to load this data. Note that in Python3, there is only the items method, which is equivalent to iteritems in Python2, and the method name iteritems has been removed.

8. Use dictionary derivation

推导式是个绝妙的东西,列表推导式一出,map、filter等函数黯然失色,自 Python2.7以后的版本,此特性扩展到了字典和集合身上,构建字典对象无需调用 dict 方法。

bad
numbers = [1,2,3]
d = dict([(number,number*2) for number in numbers])
good
numbers = [1, 2, 3]
d = {number: number * 2 for number in numbers}

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

Python中怎样把矩阵转换为列表

Python连接MySQL的方式总结

The above is the detailed content of How to use lists of Python dictionaries. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn