Home Backend Development Python Tutorial How to use lists of Python dictionaries

How to use lists of Python dictionaries

Apr 09, 2018 pm 05:54 PM
python use how

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
Copy after login

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"))
Copy after login

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")
  ]
Copy after login

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']}
Copy after login

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)
Copy after login

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)
Copy after login

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': []}
Copy after login

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")
Copy after login

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)
Copy after login

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)
Copy after login

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}
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1229
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles