python字典的一些操作

python

python实现两个字典合并

方法一:借助dict(d1.items() + d2.items())的方法

1 a={"a":1,"b":2,"c":3}

2 b= {"aa":11,"bb":22,"cc":33}

3 dict(a.items()+b.items())

4 # 结果:

5 {"a": 1, "aa": 11, "c": 3, "b": 2, "bb": 22, "cc": 33}

方法二:借助字典的update()方法

1 a={"a":1,"b":2,"c":3}

2 b= {"aa":11,"bb":22,"cc":33}

3 c={}

4 c.update(a)

5 c.update(b)

6 print(c)

7 # 结果:

8 {"a": 1, "aa": 11, "c": 3, "b": 2, "bb": 22, "cc": 33}

方法三:借助字典的dict(d1, **d2)方法

1 a={"a":1,"b":2,"c":3}

2 b= {"aa":11,"bb":22,"cc":33}

3 dict(a,**b)

4 # 结果:

5 {"a": 1, "aa": 11, "c": 3, "b": 2, "bb": 22, "cc": 33}

方法四:借助字典的常规处理方法

 1 a={"a":1,"b":2,"c":3}

2 b= {"aa":11,"bb":22,"cc":33}

3 c = {}

4for k,v in a.items():

5 c[k] = v

6for k,v in v.items():

7 c[k] = v

8print(c)

9# 结果:

10 {"a": 1, "aa": 11, "c": 3, "b": 2, "bb": 22, "cc": 33}

python 遍历字典

遍历键:

1 dict = {"Name": "Runoob", "Age": 7}

2 for i in dict:

3 print(i)

遍历值:

1 dict = {"Name": "Runoob", "Age": 7}

2 for i in dict.values()

3 print(i)

遍历键和值:

1 dict.items()

2 for key,value in dict.items():

3 print(key)

4 print(value)

以上是 python字典的一些操作 的全部内容, 来源链接: utcz.com/z/530523.html

回到顶部