用 for 循环去除字典 fruit _ price ={"苹果":8.5,"橘
子":5.8,"香蕉":4.9,"榴莲":30,"菠萝":5.2}中价格大于
10的元素,得到新的字典 new _ fruit _ price 。
fruit_price ={"苹果":8.5,"橘子":5.8,"香蕉":4.9,"榴莲":30,"菠萝":5.2}
new_fruit_price=fruit_price.copy() #先得到一个copy
for k,v in fruit_price.items():
if v > 10 :
del new_fruit_price[k] #把不要的删掉
print(new_fruit_price)
可以使用for遍历原字典的键值对,然后使用if条件判断来将价格小于等于10的项的键值对添加到新字典,最后打印下新字典的结果就可以了.
代码如下:
参考链接:
fruit_price ={"苹果":8.5,"橘子":5.8,"香蕉":4.9,"榴莲":30,"菠萝":5.2}
new_fruit_price={}
# https://blog.csdn.net/kalman2019/article/details/128300884?ydreferer=aHR0cHM6Ly93d3cuYmFpZHUuY29tL2xpbms%2FdXJsPUpUZTNqNUtZdkxwMUxBRFNEWXFsWlRaNGtwODJvdHR6TVQtLTJfMGtwenNPZWVoZkpyT2hJV1J5MWNBeFBEMXNaT1hKdUV0WUdKdHd2REZTOTJYYlFmMkw1dTBjWEI5SUdOMmRESFVHQjdtJndkPSZlcWlkPWQxN2E1ZjJkMDAwMDQ1MjgwMDAwMDAwNjY0M2YzZGNh
for name,price in fruit_price.items(): # 遍历字典的键和值
if price <=10 : # 如果当前项水果的价格小于等于10,则将其键和值添加到新字典中
# https://blog.csdn.net/m0_61791601/article/details/125639994
new_fruit_price[name]=price
# 打印新字典结果
print(new_fruit_price)
该回答引用chatgpt:
可以使用 Python 的 for 循环和字典推导式来实现该操作。具体步骤如下:
# 定义原始字典
fruit_price = {"苹果": 8.5, "橘子": 5.8, "香蕉": 4.9, "榴莲": 30, "菠萝": 5.2}
# 使用字典推导式和 for 循环创建新的字典
new_fruit_price = {key: value for key, value in fruit_price.items() if value <= 10}
# 输出新的字典
print(new_fruit_price)
运行结果如下:
{'苹果': 8.5, '橘子': 5.8, '香蕉': 4.9, '菠萝': 5.2}
解释一下代码:
定义原始字典 fruit_price,其中包含了各种水果的名称和价格。
使用字典推导式和 for 循环遍历 fruit_price 字典中的每个键值对,如果该键值对中的值小于或等于 10,则将该键值对添加到新的字典 new_fruit_price 中。
最后输出新的字典 new_fruit_price,其中只包含价格小于或等于 10 的水果