python中的过滤dict?
我是Python新手,尝试从给定的dict中仅获取某些值。我的dict如下所示:python中的过滤dict?,python,Python,我是Python新手,尝试从给定的dict中仅获取某些值。我的dict如下所示: my_dict = { "Value1": "2000", "Value2": "3000", "Value3": "4000" } for (key,value) in my_dict: if (int(value) > 2000): pr
my_dict = {
"Value1": "2000",
"Value2": "3000",
"Value3": "4000"
}
for (key,value) in my_dict:
if (int(value) > 2000):
print(value)
my_dict = {
"Value1": "2000",
"Value2": "3000",
"Value3": "4000"
}
for (key,value) in my_dict.items():
if (int(value) > 2000):
print(value)
对于高于2000的值,如何仅返回相应的(键、值)对?谢谢您的帮助。您可以试试这个-
my_dict = {
"Value1": "2000",
"Value2": "3000",
"Value3": "4000"
}
for key in my_dict:
if not int(my_dict[key]) > 2000:
my_dict.pop(key,None)
print(my_dict)
这样做的目的是删除不符合条件的密钥您可以像这样尝试.items()
:
my_dict = {
"Value1": "2000",
"Value2": "3000",
"Value3": "4000"
}
for (key,value) in my_dict:
if (int(value) > 2000):
print(value)
my_dict = {
"Value1": "2000",
"Value2": "3000",
"Value3": "4000"
}
for (key,value) in my_dict.items():
if (int(value) > 2000):
print(value)
如果字典不是太大,那么通过字典理解来重建它而不需要不需要的值可能会更便宜。“这就是[Python]的方式。”
您可以通过只对键进行迭代来实现它-当您知道字典的键时,您也知道值:
@谢谢你的关注,更新了答案。我也会使用
。dict comp可能是最干净的,但使用的内存更多,my_dict={k:v代表k,v在my_dict.items()中,如果int(v)>2000}
。谢谢,.items()简化了它。我现在在w3schools上看到了这个方法。是的,.items()完成了这个任务。
my_dict = {
"Value1": "2000",
"Value2": "3000",
"Value3": "4000"
}
for key in my_dict:
value = my_dict[key]
if int(value) > 2000:
print(key, value)