deleting entries in a dictionary based on a condition

前端 未结 1 1313
轮回少年
轮回少年 2020-12-10 03:20

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         


        
相关标签:
1条回答
  • 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().

    0 讨论(0)
提交回复
热议问题