Table of Contents
Generate dictionary from sequence
Default value of key
Exchange key and value
Sequence modification and initialization
Key, items set operation
Sort the dictionary by key or value
Multiple dictionary sorting
Home Backend Development Python Tutorial Python Dictionary: Is there any advanced gameplay that I don't know how to do?

Python Dictionary: Is there any advanced gameplay that I don't know how to do?

Apr 11, 2023 pm 11:58 PM
python dictionary code

Python Dictionary: Is there any advanced gameplay that I don't know how to do?


Generate dictionary from sequence

We convert the following sequence into dict type.

lst = [('a', 1), ('b', 2), ('c', 3)]
Copy after login

Common writing method

for k, v in lst:
dic[k] = v
Copy after login

More pythonic writing method

Use dictionary derivation to quickly generate a dictionary.

{k: v for k, v in lst}
Copy after login

Default value of key

When the specified key does not exist, set the value to 0.

Ordinary writing method

if key not in dct:
dct[key] = 0
Copy after login

pythonic writing method

dct[key] = dct.get(key, 0)
Copy after login

Exchange key and value

Ordinary writing method

dic = {'Python': 1, 'Java': 2}
new_dic = {}
for k, v in dic.items():
new_dic[v] = k
Copy after login

More pythonic writing method

dic = {'Python': 1, 'Java': 2}
new_dic = {v: k for k, v in dic.items()}

Copy after login

Sequence modification and initialization

Sample data

lst = [('a', 1), ('b', 2), ('c', 3)]
dic = {'a': [0]}
Copy after login

If we need to update the data in dic based on lst, when the key exists, the value will be added to the end of the original sequence , otherwise initialize value and save it in sequence.

Ordinary writing method

for key, value in lst:
if key in dic:
dic[key].append(value)
else:
dic[key] = [value]
Copy after login

More pythonic writing method

for (key, value) in lst:
group = dic.setdefault(key, [])
group.append(value)
# dic:{'a': [0, 1], 'b': [2], 'c': [3]}
Copy after login

setdefault(key, default) will first determine whether the key exists. If it exists, it will return dct[key], if it does not exist, it will return Then set dct[key] to [] and return.

Key, items set operation

If we now need to obtain the mapping information of the intersection of the keys of two dictionaries.

Ordinary writing method

dic1 = {'Python': 1, 'Java': 2, 'C': 3}
dic2 = {'Python': 3, 'Java': 2, 'C++': 1}
new_dic = {}
for k, v in dic1.items():
if k in dic2.keys():
new_dic[k] = v
print(new_dic)
# {'Python': 1, 'Java': 2}
Copy after login

More pythonic writing method

dic1 = {'Python': 1, 'Java': 2, 'C': 3}
dic2 = {'Python': 3, 'Java': 2, 'C++': 1}
print({k: dic1[k] for k in dic1.keys() & dic2.keys()})
# {'Python': 1, 'Java': 2}
Copy after login

The dic1.keys() & dic2.keys() here use keys() for set operations , items() can also perform set operations.

If we now want to obtain the same key and value parts in two dictionaries

dic1 = {'Python': 1, 'Java': 2, 'C': 3}
dic2 = {'Python': 3, 'Java': 2, 'C++': 1}
print(dic1.items() & dic2.items())
# {('Java', 2)}
Copy after login

Flexibly use the characteristics of keys and items() set operations to quickly extract the content we want.

Sort the dictionary by key or value

Use the sorted() function to quickly sort the key or value.

dic = {'a': 2, 'b': 1, 'c': 3, 'd': 0}
lst1 = sorted(dic.items(), key=lambda x: x[0], reverse=False)
# [('a', 2), ('b', 1), ('c', 3), ('d', 0)]
lst2 = sorted(dic.items(), key=lambda x: x[1], reverse=False)
# [('d', 0), ('b', 1), ('a', 2), ('c', 3)]
print('按照键降序:', {key: value for key, value in lst1})
print('按照值降序:', {key: value for key, value in lst2})
# 按照键降序: {'a': 2, 'b': 1, 'c': 3, 'd': 0}
# 按照值降序: {'d': 0, 'b': 1, 'a': 2, 'c': 3}
Copy after login

Multiple dictionary sorting

If a sequence contains multiple dictionaries, these dictionaries must now be sorted according to conditions. This can also be achieved using the sorted() function.

dict_list = [
{'letter': 'B', 'number': '2'},
{'letter': 'A', 'number': '3'},
{'letter': 'B', 'number': '1'}
]
# 按 letter 排序
print(sorted(dict_list,
 key=lambda dic: dic['letter']))
# 按 letter, number 排序
print(sorted(dict_list,
 key=lambda dic: (dic['letter'], dic['number'])))
# [{'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '2'}, {'letter': 'B', 'number': '1'}]
# [{'letter': 'A', 'number': '3'}, {'letter': 'B', 'number': '1'}, {'letter': 'B', 'number': '2'}]
Copy after login

Of course, if you know itemgetter(), the above code can be changed and the execution speed will be faster.

from operator import itemgetter
print(sorted(dict_list
 key=itemgetter('letter')))
print(sorted(dict_list,
 key=itemgetter('letter', 'number')))
Copy after login

itemgetter() does not obtain a value, but defines a function through which it is applied to the target object.

The above is the detailed content of Python Dictionary: Is there any advanced gameplay that I don't know how to do?. 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)

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

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.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

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.

Can vscode be used for mac Can vscode be used for mac Apr 15, 2025 pm 07:36 PM

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

Can vscode run ipynb Can vscode run ipynb Apr 15, 2025 pm 07:30 PM

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.

Golang vs. Python: Concurrency and Multithreading Golang vs. Python: Concurrency and Multithreading Apr 17, 2025 am 12:20 AM

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

See all articles