您的位置:首页 > 编程语言 > Python开发

Python数据类型--字典

2018-01-17 11:21 671 查看

Python中的字典

存储数据时不保持元素的顺序

通过任意键值查找集合中值信息的过程叫做映射,Python中通过字典实现映射。

字典是一个键值对的集合。

– 该集合以键为索引,同一个键信息对应一个值。

>>> passwd = {"China": "BigCountry", "Korean": "SmallCountry"}
>>> print(passwd)
{'China': 'BigCountry', 'Korean': 'SmallCountry'}


字典操作

为字典增加一项

dictionaryName[key] = value

使用大括号创建字典,使用中括号为字典增加一项

>>> students = {" 203":"John", "204":"Peter"}
>>> students["205"] = "Susan"
>>> print(students)
{' 203': 'John', '204': 'Peter', '205': 'Susan'}


访问字典中的值

dictionaryName[key] 返回键key对应的值value,如果没有该项,则出错。

>>> students["204"]
'Peter'
>>> students["206"]
Traceback (most recent call last):
File "<input>", line 1, in <module>
KeyError: '206'


删除字典中的一项

del dictionaryName[key]

>>> del students[" 203"]


字典的遍历

>>> for key in students:
...     print(key + " :" + str(students[key]))
...
204 :Peter
205 :Susan


遍历字典的键key

for key in dictionaryName.keys():print(key)


遍历字典的值value

for value in dictionaryName.values():print(value)


遍历字典的项

for item in dictionaryName.items():print(item)


遍历字典的key-value对

for item, value in dictionaryName.items():print(item, value)


判断一个键是否在字典中

in 或者not in


字典的标准操作符

-, <, >, <=, >=, ==, !=, and, or, not


字典不支持拼接操作符和重复操作符
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: