Home Backend Development Python Tutorial python解决字典中的值是列表问题的方法

python解决字典中的值是列表问题的方法

Jun 16, 2016 am 08:46 AM
dictionary

问题:查找一些英文词在哪些小句中出现了,当然是用python来实现,当然是用字典,但是怎么让一个key对应一个 类型为列表的value,直接用列表的append()是不行的,比如dic[key].append(value),因为解释器并不知道 dic[key]的类型,当时赶时间,用了一个折衷的方案,就是先用value连成一个str,最后用str.split()作一个转换,生成一个列表.

    看了python cookbook,上面正好有一个recipe讲到如何处理这样的问题,好了,揭晓答案吧!

(1)value中允许有重复项.

复制代码 代码如下:

dic = {}
dic.setdefault(key,[]).append(value)
#如:
d1.setdefault('bob_hu',[]).append(1)
d1.setdefault('bob_hu',[]).append(2)
print d1['bob_hu'] # [1,2]

(2)value中无重复项.

复制代码 代码如下:

dic = {}
dic.setdefault(key,{})[value] = 1
#如:
d1.setdefault('bob',{})['f'] = 1
d1.setdefault('bob',{})['h'] = 1
d1.setdefault('bob',{})['f'] = 1
print d1['bob'] #{'h': 1, 'f': 1}
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Python program to get first and last element in dictionary Python program to get first and last element in dictionary Sep 07, 2023 pm 05:01 PM

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Developed by GudioVanRossum in 1991. It supports multiple programming paradigms, including structured, object-oriented, and functional programming. Before we dive into this topic, let's review the basic concepts relevant to the questions we provide. A dictionary is a unique, mutable, and ordered set of items. Curly braces are used when writing dictionaries, and they contain keys and values: key names can be used to refer to dictionary objects. Data values ​​are stored in dictionaries in the form of key:value pairs. Ordered and unordered meaning When we say that a dictionary is ordered, we mean that its contents have a certain order and do not change. Unordered items lack a clear order and therefore cannot be used

Empty dictionary key incorrect: How to solve Python's dictionary key error? Empty dictionary key incorrect: How to solve Python's dictionary key error? Jun 24, 2023 pm 03:03 PM

The dictionary in Python is a flexible and powerful data structure that can store key-value pairs and has fast search and insertion functions. However, if you are not careful with dictionary key-value pairs, you may encounter the problem of empty dictionary keys. This problem often causes the code to crash or output unexpected results. This article will introduce two methods to solve the empty dictionary key error in Python. Method 1: Use if statements to prevent empty dictionary keys. Python dictionaries cannot have duplicate keys, otherwise the previous key-value pairs will be overwritten. When the value of a dictionary key is empty

How to get the next key in a dictionary in Python? How to get the next key in a dictionary in Python? Aug 28, 2023 pm 11:45 PM

Dictionaries are a powerful data type in Python. It consists of key-value pairs. Searching, appending and other operations can be efficiently completed through this data type. While accessing values ​​in a dictionary is simple, there may be situations where you need to look up the next key in the dictionary. Python provides several ways to achieve this, depending on your specific requirements. In this article, we will explore different ways of getting the next key in a dictionary in Python. Using the keys and index methods dictionaries are unordered collections in Python. So we first need to convert the keys into some sorted form. We can first append all keys in the form of a list. Next, we can find the next key by indexing the list. With the help of keys we can also

C++ program initialization dictionary C++ program initialization dictionary Sep 09, 2023 pm 07:01 PM

C++ differs from Python in terms of a dictionary with the same name, but it has the same data structure with similar functionality. C++ supports mapping, which can be used in the STL class std::map. The map object contains a pair of values ​​in each entry, one is the key value and the other is the map value. Key values ​​are used to search for and uniquely identify entries in the map. While mapped values ​​are not necessarily unique, key values ​​must always be unique in the map. Let's take a look at how to use mapping. First, let's see how to define a mapped data structure in C++. Syntax #includemap<data_type1,data_type2>myMap; Let’s take an example to see how to do this − Example #incl

Python program to delete null values ​​​​in the dictionary as an example Python program to delete null values ​​​​in the dictionary as an example Sep 03, 2023 pm 04:45 PM

Dictionaries are known as collection data types. They store data in the form of key-value pairs. They are ordered and mutable, i.e. they follow a specific order and are indexed. We can change the value of a key so it is manipulable or changeable. Dictionaries do not support data duplication. Each key can have multiple values ​​associated with it, but a single value cannot have multiple keys. We can perform many operations using dictionaries. The whole mechanism depends on the stored value. In this article, we will discuss the techniques you can use to remove "null values" from a dictionary. Before starting the main operation, we must have an in-depth understanding of value handling in dictionaries. Let’s take a quick overview of this article. This article is divided into two parts - Part 1st will focus on the concept of "null value" and its significance. In part 2nd

Python program to check if characters of all string elements are in lexicographic order Python program to check if characters of all string elements are in lexicographic order Aug 30, 2023 pm 08:29 PM

Lexical order refers to the order of characters or strings based on dictionary or alphabetical order. Characters are arranged in lexical order the same way they are arranged in a dictionary. The comparison is done based on the numerical value of the characters in the respective character set (such as ASCII or Unicode). In lexical order, characters are compared from left to right based on their ASCII or Unicode values. Characters with lower ASCII or Unicode values ​​precede characters with higher values. For example, in ASCII order, "a" comes before "b", "b" comes before "c", and so on. When comparing strings, lexical order is determined by comparing corresponding characters in the string from left to right. If the first character of one string is greater than another

What are the methods for converting between dictionaries and JSON in Python? What are the methods for converting between dictionaries and JSON in Python? Oct 18, 2023 am 10:30 AM

What are the methods for converting between dictionaries and JSON in Python? As a very commonly used data structure, dictionary is widely used in Python. JSON (JavaScriptObjectNotation), as a lightweight data exchange format, is also widely used in network data transmission and storage. In Python, converting between dictionaries and JSON is a common operation. This article will introduce several commonly used methods and attach corresponding code examples. square

How to add value to dictionary in Python? How to add value to dictionary in Python? Aug 20, 2023 am 08:13 AM

Python is a versatile and powerful programming language with various built-in data types. One of the most useful built-in data types in Python is dictionary, which allows us to store and retrieve data in the format of key-value pairs, and Compared to other built-in data types in Python, we can easily add or remove values ​​from the dictionary. In this article, we will discuss how to add values ​​to a dictionary in Python and the various ways to do so. What is a dictionary in Python? Before we start adding values ​​to Python dictionaries, let’s first understand what dictionaries are and how they work. In Python, we have a built-in data set called a dictionary, which is a

See all articles