!/usr/bin/env python
-*- encoding:UTF-8 -*-
字典
dict
# # # 字典的value可以是任何值 字典无序
info = {
"k1": "v1", # 键值对
"k2": "v2",
"k3": [
11,
22,
33,
[12, 12],
{
"kk1": "vv1",
"kk2": (11, 33,),
}
],
"k4": (11, 22, 33, 44,)
}
print(info)
# # # 列表和字典不可以作为key值,元组可以
info = {
123: 'jfdsl',
"K1": 'fjd;a',
(11, 22): 123
}
print(info)
# 索引查找指定元素
v = info["k1"]
print(v)
v = info[2]
print(v)
v = info["k3"][4]["kk2"][0]
# 删除指定元素
del info["k3"][4]["kk1"]
# 循环只有for
info = {
"k1": "v1", # 键值对
"k2": "v2",
"k3": [
11,
22,
33,
[12, 12],
{
"kk1": "vv1",
"kk2": (11, 33,),
}
],
"k4": (11, 22, 33, 44,)
}
# 默认输出key
for item in info:
print(item)
for item in info.keys():
print(item)
for item in info.values():
print(item)
for item in info.keys():
print(item, info[item])
for key, val in info.items():
print(key, val)
# 布尔值可以为key,True代表1,False代表0,在字典中重复key会被覆盖
info = {
1:"jfdkl",
True:1234,
0: "jfdkla;"
}
print(info)
# # # # # # #特有的
dic = {
"k1": "v1",
'k2': 124
}
# 根据系列,创建字典,并指定统一的值,
v = dict.fromkeys(["k1",1234,"555"],123)
print(v)
# 根据key获取值,不存在,输出默认值
v = dic.get("K111",1111)
print(v)
删除并获取值
v = dic.pop('k1')
print(dic, v)
k,v = dic.pop('k1', 90)
print(dic, v1)
k,v = dic.popitem()
print(dic, k, v)
# 设置值
# 已存在,不设置,获取当前key对应的值
# 不存在,设置,获取当前key对应的值
dic = {
"k1": "v1",
'k2': 124
}
v = dic.setdefault("k1798","123")
print(dic,v)
dic = {
"k1": "v1",
'k2': 124
}
dic.update({'k1': '112231','k3':123456})
print(dic)
dic.update(k1=1244312,k3=14312,k5="dksa")
print(dic)
keys() values() items() get uodate