search
HomeBackend DevelopmentPython TutorialHow to use lists of Python dictionaries

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
Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

How can you make a Python script executable on both Unix and Windows?How can you make a Python script executable on both Unix and Windows?May 06, 2025 am 12:13 AM

TomakeaPythonscriptexecutableonbothUnixandWindows:1)Addashebangline(#!/usr/bin/envpython3)andusechmod xtomakeitexecutableonUnix.2)OnWindows,ensurePythonisinstalledandassociatedwith.pyfiles,oruseabatchfile(run.bat)torunthescript.

What should you check if you get a 'command not found' error when trying to run a script?What should you check if you get a 'command not found' error when trying to run a script?May 06, 2025 am 12:03 AM

When encountering a "commandnotfound" error, the following points should be checked: 1. Confirm that the script exists and the path is correct; 2. Check file permissions and use chmod to add execution permissions if necessary; 3. Make sure the script interpreter is installed and in PATH; 4. Verify that the shebang line at the beginning of the script is correct. Doing so can effectively solve the script operation problem and ensure the coding process is smooth.

Why are arrays generally more memory-efficient than lists for storing numerical data?Why are arrays generally more memory-efficient than lists for storing numerical data?May 05, 2025 am 12:15 AM

Arraysaregenerallymorememory-efficientthanlistsforstoringnumericaldataduetotheirfixed-sizenatureanddirectmemoryaccess.1)Arraysstoreelementsinacontiguousblock,reducingoverheadfrompointersormetadata.2)Lists,oftenimplementedasdynamicarraysorlinkedstruct

How can you convert a Python list to a Python array?How can you convert a Python list to a Python array?May 05, 2025 am 12:10 AM

ToconvertaPythonlisttoanarray,usethearraymodule:1)Importthearraymodule,2)Createalist,3)Usearray(typecode,list)toconvertit,specifyingthetypecodelike'i'forintegers.Thisconversionoptimizesmemoryusageforhomogeneousdata,enhancingperformanceinnumericalcomp

Can you store different data types in the same Python list? Give an example.Can you store different data types in the same Python list? Give an example.May 05, 2025 am 12:10 AM

Python lists can store different types of data. The example list contains integers, strings, floating point numbers, booleans, nested lists, and dictionaries. List flexibility is valuable in data processing and prototyping, but it needs to be used with caution to ensure the readability and maintainability of the code.

See all articles

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.