从字典数组中删除元素

时间:2019-01-27 11:05:48

标签: python dictionary

first_obj = [{"%name":"sat","age":20,"%country":"India"},
             {"%name":"sat","age":20,"%country":"India"}]

如何删除不以%开头的元素

first_obj= [{"%name":"sat","%country":"India"},
            {"%name":"sat","%country":"India"}]

2 个答案:

答案 0 :(得分:0)

这就是你想要的

first_obj  = [{"%name":"sat","age":20,"%country":"India"},
             {"%name":"sat","age":20,"%country":"India"}]

first_obj  = [{x:d[x] for x in d.keys() if x.startswith("%")} for d in first_obj]

答案 1 :(得分:-1)

您可以通过删除键来从字典中删除键/值对:

for sub_dict in first_obj:
    for key in list(sub_dict.keys()):
        if not key.startswith('%'):
            del sub_dict[key]

我制作了键的列表副本,因为在迭代过程中修改容器可能会导致错误。