码迷,mamicode.com
首页 > 编程语言 > 详细

Python基础--字典(dictionary)

时间:2018-06-13 15:09:16      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:字典   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)

Python基础--字典(dictionary)

标签:字典   dictionary   

原文地址:http://blog.51cto.com/13803166/2128809

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!