标签:字典 dictionary
1.字典的定义,键唯一,值随意dic={key0:value0,key1:value1}
2.输出
print(dic[key0])
>>:value0
3.遍历字典
3.1keys()遍历字典中的key
dic={‘name‘:‘zhangsan‘,‘age‘:20}
for k in dic.keys():
print(k)
>>:
name
age
3.2values()遍历字典中的value
dic={‘name‘:‘zhangsan‘,‘age‘:20}
for v in dic.values():
print(v)
>>:
zhangsan
20
3.3items()遍历字典中的key,value
dic={‘name‘:‘zhangsan‘,‘age‘:20}
for k,v in dic.items():
print(k+‘:‘+str(v))
>>:
name:zhangsan
age:20
4.字典插入元素
dic={‘name‘:‘zhangsan‘,‘age‘:20}
dic[‘job‘]=‘python‘
print(dic)
>>:
{‘name‘: ‘zhangsan‘, ‘age‘: 20, ‘job‘: ‘python‘}
5.根据键修改值
dic={‘name‘:‘zhangsan‘,‘age‘:20}
dic[‘name‘]=‘lisi‘
print(dic)
>>:
{‘name‘: ‘lisi‘, ‘age‘: 20}
6.pop()删除字典中的元素
dic={‘name‘:‘zhangsan‘,‘age‘:20}
dic.pop(‘name‘)
print(dic)
>>:
{‘age‘: 20}
7.判读元素是否在字典中:
dic={‘name‘:‘zhangsan‘,‘age‘:20}
tmp=‘name‘
if tmp in dic:#和 if tmp in dic.keys()相同:
print("%s in dic" %tmp)
#判断元组是否在值中
if tmp in dic.values():
print("%s in dic" %tmp)
标签:字典 dictionary
原文地址:http://blog.51cto.com/13803166/2128809