字典的魔法

  1. 云栖社区>
  2. 博客>
  3. 正文

字典的魔法

陈天刚 2018-04-03 23:17:30 浏览624
展开阅读全文

dict

创建一个字典

info = {
    "k1": "v1",
    "k2":"v2"
}

字典value

info = {
    "k1":18,
    "k2":True,
    "k3":[
        11,
        22,
        33,
        {
            'kk1':'vv1',
            'kk2':'vv2',
            'kk3':'vv3'
        }
    ]
}
print(info)
---
{'k3': [11, 22, 33, {'kk3': 'vv3', 'kk1': 'vv1', 'kk2': 'vv2'}], 'k2': True, 'k1': 18}

布尔值为key时,如果有数字1或0为key时,可能会重复,key需要是唯一的。

info = {
    1:'asdf',
    "hehe":"asdf",
    True:"123"
}
print(info)
---
{1: '123', 'hehe': 'asdf'}

要点

  • 数字允许为key
  • 列表不能做为字典的key
  • 字典也不能做为字典的key
  • 字典是无序的。
  • 字典可以循环,默认循环所有的key

字典取值

v = info["k1"]
print(v)
---
18

通过索引的方式找到指定的值。

v = info["k3"][3]["kk3"][0]
print(v)
---
11

删除键值对

del info['k1']
print(info)
---
{'k2': True, 'k3': [1, 22, 33, {'kk2': 'vv2', 'kk3': [11, 22, 33], 'kk1': 'vv1'}]}

del info['k3'][3]['kk1']
print(info)
---
{'k1': 18, 'k3': [1, 22, 33, {'kk2': 'vv2', 'kk3': [11, 22, 33]}], 'k2': True}

找出所有的key

for item in info.keys():      #不使用keys()方法默认循环所有key
   print(item,info(item))
---
k1
k3
k2

找出所有的values

for item in info.values():
    print(item)
---
True
18
[1, 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': [11, 22, 33]}]

同时取出key,values------> items()方法

for k,v in info.items():
    print(k,v)
---
k3 [1, 22, 33, {'kk1': 'vv1', 'kk2': 'vv2', 'kk3': [11, 22, 33]}]
k1 18
k2 True

字典中的方法

def items()
def values()
def items()
def update()
def clear()
def copy()
def fromkeys()
def get()
def pop()
def popitem()

根据序列创建字典,并指定统一的值---fromkeys

dic = {
    "k1":"v1"
}
v = dict.fromkeys(["k1",123,"999"],123)
print(v)
---
{123: 123, 'k1': 123, '999': 123}

根据key获取值,key不存在时,可以指定默认值,默认值不存在是返回None

dic = {
    "k1":"v1"
}
v = dic.get('k1')
print(v)
---
v1
# 当要取的key在字典中没有时不会报错,返回None
v = dic.get('kkk',1111)
print(v)
---
1111

删除key,并获取值 pop

dic = {
    "k1":"v1",
    "k2":"v2"
}
dic.pop('k1')
print(dic)
---
{'k2': 'v2'}

v = dic.pop('k1')
print(dic,v)
---
{'k2': 'v2'} v1

# pop后可以加默认值,当值不存在时可以返回默认值
v = dic.pop('k1',90)
···
#### 设置默认值 setdefault

v = dic.setdefault('k3','12') #当值key值存在时,不改变,不存在加上

print(dic,v)

{'k3': '12', 'k1': 'v1', 'k2': 'v2'} 12

#### 更新

dic = {

"k1":"v1",
"k2":"v2"

}
v = dic.update({'k1':'1111','k3':123})

print(dic,v)

{'k3': 123, 'k1': '1111', 'k2': 'v2'} None

第二种写法

dic.update(k1=123,k3=123,k4="asdf") #python默认转换为字典

## 总结
#### 1.数字
int(...)
#### 2.字符串

replace/find/join/strip/startswith/split/upper/lower/format
template = "i am {name}, age: {age}"
v = template.format(name='alex',age=19)
v = template.format(**{"name": 'alex', 'age': 19)
print(v)

#### 3.列表

append/extend/insert
索引、切片、循环

#### 4.元组
忽略
索引、切片、循环,以及元素不能被修改删除等

#### 5.字典

get / update / keys / values / items
for 索引
v = "k1" in dic.values()

print(v)

False

#### 6.布尔值

0 1
bool(...)
False------> None "" "{}" "[]" "()" 0

网友评论

登录后评论
0/500
评论
陈天刚
+ 关注