Python items()方法

items() 方法的遍历:items() 方法把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回

'''
将字典⾥的值是数值型的转换为字符串,如a = {‘aa’: 11, ‘bb’: 222}
得到{‘aa’: ‘11’, ‘bb’: ‘222’}

'''

def test():
a = {'aa' : 11, 'bb' : 222}

# print(a.items()) dict_items([('aa', 11), ('bb', 222)])

for i in a.items():
a.update({i[0] : str(i[1])})
return a

 

 

'''
m1 = {'a':1 , 'b':2 , 'c':1} # 将同样的value的key集合在list⾥,输出 {1: ['a', 'c'], 2: ['b']}

'''
def test():

m1 = {'a':1 , 'b':2 , 'c':1}

new_dict = {}

# 循环 m1 字典 中的数据

# print(m1.items()) dict_items([('a', 1), ('b', 2), ('c', 1)])
for key, value in m1.items():

# 判断如果m1 字典中的值 不在新定义 的new_dist 字典中

if value not in new_dict:

#则往新字典中添加键值对
new_dict[value] =[key]
else:
# 如果添加的键已经存在了,则直接添加值
new_dict[value].append(key)
return new_dict

print(test())

 

 



 

posted @ 2022-05-05 20:55  大熊童鞋  阅读(1733)  评论(0编辑  收藏  举报