一、字典的概念:
字典是一种键值对的结构,类似于通过联系人姓名查找地址和联系人详细情况的地址簿,即把键(姓名)和值(联系人的详细情况)联系在一起。
Note:键必须是唯一的,如果有两个人碰巧同名,则无法找到正确的信息。
键值对在字典中以如下的方式进行标记:
{key1 : value1 ,key2 : value2 ,………… }
Note:键值对内部用冒号进行分隔,对与对之间则使用逗号进行分隔,所以这些键值对,则包含在花括号中。
示例如下:
1)、 新建一个空的字典
dict = {}
2)、 在上面空的字典中,输入值:
dict["test1"]= 123456789
dict["test2"] = 987654321
3 )、将值直接以键值对的形式传入字典中 :
dict = {"test3" : 98745621, "test4" : 369852147}
以上完整的实例代码如下:
#!/usr/bin/env python
#新建一个空的字典
dict = {}
#在上面空的字典中,输入值
dict["test1"]= 123456789
dict["test2"] = 987654321
print(dict)
#将值直接以键值对的形式传入字典中
dict = {"test3" : 98745621, "test4" : 369852147}
print(dict)
二、字典的方法:
1)、keys()
keys()方法用来获取字典内的所有键。
#!/usr/bin/env python
dict = {"test3" : 98745621, "test4" : 369852147}
print(dict.keys())
执行结果如下:
dict_keys(['test3', 'test4'])
2)、values()
values()方法用来获取字典内的所有值。
#!/usr/bin/env python
dict = {"test3" : 98745621, "test4" : 369852147}
print(dict.values())
执行结果如下:
dict_values([98745621, 369852147])
3)、items()
items()方法用来得到一组组的键值对
#!/usr/bin/env python
dict = {"test3" : 98745621, "test4" : 369852147}
print(dict.items())
执行结果如下:
dict_items([('test3', 98745621), ('test4', 369852147)])