0
点赞
收藏
分享

微信扫一扫

Python items()方法

代码小姐 2022-08-29 阅读 64

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

Python items()方法_元组

 

 

'''
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())

Python items()方法_字符串_02

 

 

 

世界上最美的风景,是自己努力的模样



举报

相关推荐

0 条评论