基于条件删除字典中的条目 [英] deleting entries in a dictionary based on a condition

查看:116
本文介绍了基于条件删除字典中的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名称为关键字的字典,(年龄,出生日期)元组为这些键的值。例如

  dict = {'Adam':(10,'2002-08-13'),
'Eve ':(40,'1972-08-13')}

我想删除所有的键年龄> 30岁,价值元组,我该怎么做?我正在使用 dict [name] [0] 其中dict是我的字典访问每个密钥的年龄。

解决方案

通常的方法是创建一个仅包含您要保留的项目的新字典:

  new_data = {k:v for k,v in data.iteritems()if v [0] <= 30} 

在Python 3.x中,使用 items()而不是 iteritems() p>

如果您需要更改原来的字典,可以使用 -loop:

  for k,v in data.items():
if v [0]> 30:
del data [k]

在Python 3.x中,使用 list(data.items())而不是 data.items()


I have a dictionary with names as key and (age, Date of Birth) tuple as the value for those keys. E.g.

dict = {'Adam' : (10, '2002-08-13'),
        'Eve'  : (40, '1972-08-13')}

I want to delete all the keys which have age > 30 for their age in value tuple, how can I do that? I am accessing age of each key using dict[name][0] where dict is my dictionary.

解决方案

The usual way is to create a new dictionary containing only the items you want to keep:

new_data = {k: v for k, v in data.iteritems() if v[0] <= 30}

In Python 3.x, use items() instead of iteritems().

If you need to change the original dictionary in place, you can use a for-loop:

for k, v in data.items():
    if v[0] > 30:
        del data[k]

In Python 3.x, use list(data.items()) instead of data.items().

这篇关于基于条件删除字典中的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆