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

Python基础知识---字典

时间:2016-10-13 02:14:32      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:

    现在在实习期间,好久没用Python了,今天在做Java项目时用的HashMap让我联想到了Python中的字典,就写一些Python字典的知识吧,复习复习。

    

     字典:  key --> value的映射关系,字典是无序性的,字典的key是不可变类型的,如int, str, float,tuple...

1.创建字典

  (1)第一种方式创造字典,一次给全

>>> user = {‘id‘: 1000, ‘name‘: ‘scd‘, ‘password‘:‘123‘}
>>> user
{‘password‘: ‘123‘, ‘id‘: 1000, ‘name‘: ‘scd‘}

   (2)d[key] = value

>>> user = { }
>>> user[‘id‘] = 1000
>>> user[‘name‘] = ‘scd‘
>>> user[‘password‘] = ‘123‘
>>> user
{‘password‘: ‘123‘, ‘id‘: 1000, ‘name‘: ‘scd‘}
>>>

    (3)d = dict(zip(key, value)),   这里key, value是列表

>>> key = [‘id‘, ‘name‘, ‘password‘]
>>> value = [1000, ‘scd‘, ‘123‘]
>>> user = dict(zip(key, value))
>>> user
{‘password‘: ‘123‘, ‘id‘: 1000, ‘name‘: ‘scd‘}
>>>

   第2种创建字典的方法经常用到

2.字典遍历

 

>>> for key in user:
...     print key, ":", user[key]
...
password : 123
id : 1000
name : scd
>>>

    经常使用的是创建字典的第(2)种方式和字典的遍历,关于其它的字典方法明天再继续写

 

Python基础知识---字典

标签:

原文地址:http://www.cnblogs.com/shootercheng/p/5954583.html

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