当前位置:   article > 正文

python 字典的常见方法

python 字典的常见方法

1、获取字典的值

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }


print students_info["zhangsan"]              # {'age': 15, 'score': 80}
print students_info["zhangsan"]["score"]     # 80
print print students_info["xiaoming"]

Traceback (most recent call last):
  File "xxx.py", line 87, in <module>
    print students_info["xiaoming"]
KeyError: 'xiaoming'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

2、添加数据(键值对)

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }


students_info["xiaoming"] = {"age": 15, "score": 100}
print students_info

# {'lisi': {'age': 14, 'score': 90}, 'xiaoming': {'age': 15, 'score': 100}, 'zhangsan': {'age': 15, 'score': 80}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3、删除数据(键值对)

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

del students_info["zhangsan"]
print students_info
# {'lisi': {'age': 14, 'score': 90}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

4、修改数据(键值对)

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }


students_info["lisi"] = {"age": 14, "score": 95}
print students_info  
# {'lisi': {'age': 14, 'score': 95}, 'zhangsan': {'age': 15, 'score': 80}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

5、判断键值对是否存在

如果要判断字典是否包含指定的 key,则可以使用 in 或 not in 运算符。需要指出的是,对于 dict 而言,in 或 not in 运算符都是基于 key 来判断的

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

print ("lisi" in students_info)       # True
print ("age" in students_info)        # False
print ("age" in students_info["zhangsan"])   # True
print ("xioaming" in students_info)   # False

print ("age" not in students_info)    # True
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

6、clear()方法

clear() 用于清空字典中所有的 key-value 对,对一个字典执行 clear() 方法之后,该字典就会变成一个空字典。

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

students_info.clear()
print students_info      #{}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

7、get()方法

get() 方法其实就是根据 key 来获取 value,它相当于方括号语法的增强版,当使用方括号语法访问并不存在的 key 时,字典会引发 KeyError 错误;但如果使用 get() 方法访问不存在的 key,该方法会简单地返回 None,不会导致错误

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

print students_info.get("zhangsan")   # {'age': 15, 'score': 80}
print students_info.get("xiaoming")   # None
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

8、update()方法

update() 方法可使用一个字典所包含的 key-value 对来更新己有的字典。在执行 update() 方法时,如果被更新的字典中己包含对应的 key-value 对,那么原 value 会被覆盖;如果被更新的字典中不包含对应的 key-value 对,则该 key-value 对被添加进去。

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

students_info.update({"zhangsan":{"age": 15, "score": 100}})
print students_info
# {'lisi': {'age': 14, 'score': 90}, 'zhangsan': {'age': 15, 'score': 100}, 'wangwu': {'age': 16, 'score': 70}}
students_info.update({"xiaoming":{'age': 18, 'score': 85}})
print students_info
# {'lisi': {'age': 14, 'score': 90}, 'xiaoming': {'age': 18, 'score': 85}, 'zhangsan': {'age': 15, 'score': 100}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

9、items()方法

以列表返回可遍历的(键, 值) 元组数组

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }


print students_info.items()
# [('lisi', {'age': 14, 'score': 90}), ('zhangsan', {'age': 15, 'score': 80}), ('wangwu', {'age': 16, 'score': 70})]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

10、 keys()方法

以列表返回一个字典所有的键

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }


print students_info.keys()          # ['lisi', 'zhangsan', 'wangwu']
print students_info["zhangsan"].keys()   # ['age', 'score']
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

11、values()方法

以列表返回字典中的所有值

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

print students_info.values()           # [{'age': 14, 'score': 90}, {'age': 15, 'score': 80}, {'age': 16, 'score': 70}]
print students_info["wangwu"].values()  # [16, 70]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

12、pop()方法

pop() 方法用于获取指定 key 对应的 value,并删除这个 key-value 对

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

students_info.pop("lisi")
print students_info   # {'zhangsan': {'age': 15, 'score': 80}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

13、popitem()方法

popitem() 方法用于弹出字典中最后一个key-value对

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

students_info.popitem()
print students_info   # {'zhangsan': {'age': 15, 'score': 80}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

14、setdefault()方法

setdefault() 方法也用于根据 key 来获取对应 value 的值。但该方法有一个额外的功能,即当程序要获取的 key 在字典中不存在时,该方法会先为这个不存在的 key 设置一个默认的 value,然后再返回该 key 对应的值。

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

students_info.setdefault("zhangsan", {"age": 20, "score": 80})
print students_info
# {'lisi': {'age': 14, 'score': 90}, 'zhangsan': {'age': 15, 'score': 80}, 'wangwu': {'age': 16, 'score': 70}}
students_info.setdefault("xiaoming", {"age": 18, "score": 75})
print students_info
# {'lisi': {'age': 14, 'score': 90}, 'xiaoming': {'age': 18, 'score': 75}, 'zhangsan': {'age': 15, 'score': 80}, 'wangwu': {'age': 16, 'score': 70}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

15、fromkeys()方法

fromkeys() 方法使用给定的多个key创建字典,这些key对应的value默认都是None;也可以额外传入一个参数作为默认的value。该方法一般不会使用字典对象调用(没什么意义),通常会使用 dict 类直接调用

score_info = dict.fromkeys(["zhangsan", "lisi"])
print score_info
# {'lisi': None, 'zhangsan': None}
score_info = dict.fromkeys(("zhangsan", "lisi"), 80)
print score_info
# {'lisi': 80, 'zhangsan': 80}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

16、len()方法

计算字典元素个数,即键的总数

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

print len(students_info)    # 3          
print len(students_info["zhangsan"])  # 2
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

17、str()方法

输出字典可打印的字符串

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

print str(students_info)      # {'lisi': {'age': 14, 'score': 9
print str(students_info["lisi"])   #  {'age': 14, 'score': 90} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

18、type()方法

返回输入的变量类型,如果变量是字典就返回字典类型

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

print type(students_info)  # <type 'dict'>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

19、遍历key的值

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

for key in students_info:                
    print key                            
"""                                      
lisi                                     
zhangsan                                 
wangwu                                   
"""                                      
                                         
for key in students_info["wangwu"]:      
    print key                            
                                         
"""                                      
age                                      
score                                    
"""                                      
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

19、遍历value的值

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

for value in students_info.values():                                                   
    print value                                                                        
                                                                                       
"""                                                                                    
{'age': 14, 'score': 90}                                                               
{'age': 15, 'score': 80}                                                               
{'age': 16, 'score': 70}                                                               
"""                                                                                    
                                                                                       
for value in students_info["lisi"].values():                                           
    print value                                                                        
                                                                                       
"""                                                                                    
14                                                                                    
90                                                                                    
"""                                                                                    
                                                                                       
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

20、遍历字典键值对

students_info = {"zhangsan": {"age": 15, "score": 80},
                 "lisi": {"age": 14, "score": 90},
                 "wangwu": {"age": 16, "score": 70}
                 }

# 返回字符串
for key in students_info:                           
    print key + ":" + str(students_info[key])       
                                                    
"""                                                 
lisi:{'age': 14, 'score': 90}                       
zhangsan:{'age': 15, 'score': 80}                   
wangwu:{'age': 16, 'score': 70}                     
"""    

# 返回元组
for i in students_info.items():                                                               
    print i                                                                                   
                                                                                              
"""                                                                                           
('lisi', {'age': 14, 'score': 90})                                                            
('zhangsan', {'age': 15, 'score': 80})                                                        
('wangwu', {'age': 16, 'score': 70})                                                          
"""                                                                                           
 
  
for key, value in students_info.items():
    print key + ":" + str(value)

"""
lisi:{'age': 14, 'score': 90}
zhangsan:{'age': 15, 'score': 80}
wangwu:{'age': 16, 'score': 70}
"""

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

参考文档:

https://www.itcast.cn/news/20211221/15221563284.shtml#mark-H3-103

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/714519
推荐阅读
相关标签
  

闽ICP备14008679号