简体   繁体   中英

Extract specific dictionaries from a list of nested dictionaries to a temp list

I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first

It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.

This is a simple version of what I am trying to do:

[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]

So basically the keys with value "0" get copied to a temp list of dictionaries.

As I mentioned in a comment I'm not sure this will solve your problem, but based on the sample transformation you gave, here's one way to achieve it:

LIST_IN = [{"name": {"book1": "0", "book2": "1", "book3": "0"}}]

def proccess(list_in):
    result = []

    for this_dict in list_in:
        for key in this_dict["name"]:
            if this_dict["name"][key] == "0":
                result.append({key: this_dict["name"][key]})

    return result

print(proccess(LIST_IN))

This should accomplish the "sample" snippet. Please give some additional details if this is not what you were trying.

def solve_nested(nested_dict: list) -> list:
    result = list()
    for dictionary in nested_dict:
        for k, v in dictionary.items():
            for _k, _v in v.items():
                if _v == '0':
                    result.append({_k: _v})
    return result


if __name__ == '__main__':
    print(solve_nested([{"name": {"book1": "0", "book2": "1", "book3": "0"}}]))

If you're interested in recursion, the below example ought to get you going:

# d_xy => x = nest level
#         y = dictionary item in nest level x

d = {'d_00' : {'d_10' : {'d_20' : 0,
                         'd_21' : 43,
                         'd_22' : 12},
               'd_11' : 4,
               'd_12' : 0,
               'd_13' : 1},
     'd_01' : 0,
     'd_02' : {'d_14' : {'d_23' : 0,
                         'd_24' : 1,
                         'd_25' : 0},
               'd_15' : 4,
               'd_16' : {'d_26' : 0,
                         'd_27' : {'d_30' : 3,
                                   'd_31' : 0,
                                   'd_32' : {'d_40' : 0},
                                   'd_33' : 0},
                         'd_28' : 1},
               'd_17' : 0}}

important_items = []

def get_0_key_values(dic):

    for key in dic:
        if type(dic[key]) == dict:
            get_0_key_values(dic[key])
        else:
            if dic[key] == 0:
                important_items.append({key : dic[key]})

get_0_key_values(d)

print(important_items)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM