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

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

WBOY
Release: 2016-06-16 08:46:47
Original
1140 people have browsed it

问题:查找一些英文词在哪些小句中出现了,当然是用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}
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template