vkaul11
vkaul11

Reputation: 4214

ordering the dictionary values in list based on the position in the keys

I have a dictionary where the value is a list of a few substrings from the key which is a string. For example:

d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}

and I want to get a list of lists generated from list values based on the position they appeared in the key. For example in the case above:

output = [["How", "going"], ["What", "hell"], ["police", "dept"]]

I did not find an efficient way to do it so I used a hacky approach:

final_output = []
for key,value in d.items():
    if len(value) > 1:
       new_list = []
       for item in value:
          new_list.append(item, key.find(item)) 
       
          new_list.sort(key = lambda x: x[1]) 
       ordered_list = [i[0] for i in new_list] 
       final_ouput.append(ordered_list)
     

Upvotes: 1

Views: 52

Answers (3)

Yugandhar Chaudhari
Yugandhar Chaudhari

Reputation: 3984

Keys are already sorted so we can skip sorting

we can split key on " " and filter the splitted by associated value in dict

d = {"How are things going": ["going","How"], "What the hell" : ["What", "hell"], "The police dept": ["dept","police"]}

lists = []
for k in d.keys():
    to_replace = k.split(" ")
    replaced = filter(lambda x: x in d[k],to_replace)
    lists.append(list(replaced))

print(lists)

Output:

[['How', 'going'], ['What', 'hell'], ['police', 'dept']]

Upvotes: 0

ljose
ljose

Reputation: 1

Using List Comprehension

output = [[each_word for each_word in key.split() if each_word in value] for key, value in d.items()]

Upvotes: 0

Chris
Chris

Reputation: 29752

Use sorted with str.find:

[sorted(v, key=k.find) for k, v in d.items()]

Output:

[['How', 'going'],
 ['What', 'hell'], 
 ['police', 'dept']]

Upvotes: 6

Related Questions