Home > Backend Development > Python Tutorial > Can a key in a python dictionary only have one value?

Can a key in a python dictionary only have one value?

爱喝马黛茶的安东尼
Release: 2019-06-25 17:43:28
Original
8022 people have browsed it

Can a key in a python dictionary only have one value?

Can a key in a python dictionary only have one value? Let me give you a detailed introduction to multiple values ​​​​with one key:

python Chinese dictionaries can have multiple values ​​per key, which means that one key can correspond to multiple values.

Example:

#encoding=utf-8
 
print '中国'
 
#字典的一键多值
 
print'方案一 list作为dict的值 值允许重复'  
 
d1={}
key=1
value=2
d1.setdefault(key,[]).append(value)
value=2
d1.setdefault(key,[]).append(value)
 
print d1
 
#获取值
print '方案一 获取值'
print list(d1[key])
 
print '方案一 删除值,会留下一个空列表'
d1[key].remove(value)
d1[key].remove(value)
print d1 
 
print '方案一 检查是否还有一个值'
print d1.get(key,[])
 
print '方案二 使用子字典作为dict的值 值不允许重复'
 
d1={}
key=1
keyin=2
value=11
d1.setdefault(key,{})[keyin]=value
keyin=2
value=22
d1.setdefault(key,{})[keyin]=value
keyin=3
value=33
d1.setdefault(key,{})[keyin]=value
 
print d1
 
print '方案二 获取值'
print list(d1[key])
 
print '方案二 删除值,会留下一个空列表'
del d1[key][keyin]
keyin=2
del d1[key][keyin]
print d1
 
print '方案二 检查是否还有一个值'
print d1.get(key,())
 
print '方案三 使用set作为dict的值 值不允许重复'
d1={}
key=1
value=2
d1.setdefault(key,set()).add(value)
value=2
d1.setdefault(key,set()).add(value)
value=3
d1.setdefault(key,set()).add(value)
 
print d1
 
print '方案三 获取值'
print list(d1[key])
 
print '方案三 删除值,会留下一个空列表'
d1[key].remove(value)
value=2
d1[key].remove(value)
print d1 
 
print '方案三 检查是否还有一个值'
print d1.get(key,())
Copy after login

Related recommendations: "python video tutorial"

The printing results are as follows:

中国
方案一 list作为dict的值 值允许重复
{1: [2, 2]}
获取值
[2, 2]
删除值,会留下一个空列表
{1: []}
检查是否还有一个值
[]
方案二 使用子字典作为dict的值 值不允许重复
{1: {2: 22, 3: 33}}
获取值
[2, 3]
删除值,会留下一个空列表
{1: {}}
检查是否还有一个值
{}
方案三 使用set作为dict的值 值不允许重复
{1: set([2, 3])}
获取值
[2, 3]
删除值,会留下一个空列表
{1: set([])}
检查是否还有一个值
set([])
Copy after login

The above is the detailed content of Can a key in a python dictionary only have one value?. For more information, please follow other related articles on the PHP Chinese website!

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