python字典结构化数据

https://www.cnblogs.com/evablogs/p/6692947.html

 

dict:

键-值(key-value)对集合{key:value},查找速度极快,但浪费内存。

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
>>> dict = {'Name''Zara''Age'7'Class''First'}
>>> dict
{'Age'7'Name''Zara''Class''First'}
>>> dict.keys()                                                         #keys():以列表返回字典所有的键
['Age''Name''Class']
>>> dict.values()                                                       #values():以列表返回字典的所有键值
[7'Zara''First']
>>> dict.items()                                                        #items():以列表返回字典的所有键值对
[('Age'7), ('Name''Zara'), ('Class''First')]
>>> dict['Class']='Second'                                              #更新键值,覆盖存在的键值,默认存取后面更新的值
>>> dict
{'Age'7'Name''Zara''Class''Second'}
>>> dict['Class']
'Second'
>>> dict.get('age',18)                                                  #get('键',默认值):返回键值,如果键值不存在返回默认值不报错
18
>>> 'Name' in dict.keys()                                               #判断键是否存在,返回值为True/False
True
>>> 7 in dict.values()                                                  #判断值是否存在
True
>>> dict.clear()                                                        #清空字典中所有元素
>>> dict
{}
>>> del dict                                                            #删除字典
>>> dict
<type 'dict'>

set:无序集合,自动去重

1
2
3
4
5
6
7
8
9
>>> s=set([1,2,3,4,5,5])
>>> s
set([12345])                                                    #自动去除重复的值
>>> s.add(6)                                                            #add():新增一个元素
>>> s
set([123456])
>>> s.remove(1)                                                         #remove():移除元素
>>> s
set([23456])
posted @ 2019-04-29 14:56  爱笑的小宇宙  阅读(345)  评论(0编辑  收藏  举报