Reformating a dictionary of list based on items in another list

Viewed 54

I have a dictionary of lists like

source = {"name":["hans","james","mat"],"country":["spain"],"language":["english","french"]}

and another list like

data_not_avail = ["hans","spain","mat"]

How is it possible to reformat source dictionary into the following format

{
 "exist":{"name":["james"], "language":["english","french"]},
 "not_exist":{"name":["hans","mat"], "country":["spain"]}
}

I was trying to solve by finding the key of item which are present in list but it was not a success

data_result = {}
keys_list = []
for v in data_not_avail:
    keys = [key for key, value in source.items() if v in value]
    data_result.update({keys[0]:[v]})
    keys_list.extend(keys)
2 Answers

This is a approach, you can use a list comprehension (or python built in filter) to filter every element within source lists with the content of data_not_avail.

data = {"exist": {}, "not_exist": {}}

for key, value in source.items():
    data["exist"][key] = [v for v in value if v not in data_not_avail]
    data["not_exist"][key] = [v for v in value if v in data_not_avail]

    # if you dont need empty list in the result
    if not data["exist"][key]:
        del data["exist"][key]

    if not data["not_exist"][key]:
        del data["not_exist"][key]

Naive way of solving it is this, check it out.

values = list(source.values())
exist_values = []
not_values = []

for l in values:
    temp_exist = []
    temp_not = []
    for item in l:
        if item not in data_not_avail:
            temp_exist.append(item)
        else:
            temp_not.append(item)
    
    exist_values.append(temp_exist)
    not_values.append(temp_not)
    

exist = {}
not_exist = {}

keys = ['name', 'language', 'country']

for i,key in enumerate(keys):
    if len(exist_values[i]) != 0:
        exist[key] = exist_values[i]
    
    if len(not_values[i]) != 0:
        not_exist[key] = not_values[i]
        
print(exist, not_exist)
#{'name': ['james'], 'country': ['english', 'french']} 
#{'name': ['hans', 'mat'], 'language': ['spain']}
Related