How to match two lists and insert into specific value?

Viewed 49

I have two lists

a = ['b','c','a','d','v']
g = [{'c':'1'},{'c':'2'},{'c':'3'},{'d':'1'},{'d':'2'}]

I want to match the key in the dictionary in the list g to the elements in list a, if they are matched, the elements in list g will be inserted into list a.

The desired outcome is:

['b','c',{'c':'1'},{'c':'2'},{'c':'3'},'a','d',{'d':'1'},{'d':'2'},'v']
3 Answers

Try using sorted:

print(sorted(a + g, key=lambda x: list(x)[0]))

Output:

['a', 'b', 'c', {'c': '1'}, {'c': '2'}, {'c': '3'}, 'd', {'d': '1'}, {'d': '2'}, 'e']

Try:

a = ["b", "c", "a", "d", "v"]
g = [{"c": "1"}, {"c": "2"}, {"c": "3"}, {"d": "1"}, {"d": "2"}]

tmp = {}
for d in g:
    for k in d:
        tmp.setdefault(k, []).append(d)

out = []
for v in a:
    out.append(v)
    out.extend(tmp.get(v, []))

print(out)

Prints:

['b', 'c', {'c': '1'}, {'c': '2'}, {'c': '3'}, 'a', 'd', {'d': '1'}, {'d': '2'}, 'v']
a = ['a','b','c','d','e']
g = [{'c':'1'},{'c':'2'},{'c':'3'},{'d':'1'},{'d':'2'},{'z':'1'}]

for dic in g:
    for key in dic:
        if key in a:
            a.append(dic)
print(a)

#output ['a', 'b', 'c', 'd', 'e', {'c': '1'}, {'c': '2'}, {'c': '3'}, {'d': '1'}, {'d': '2'}]

After this, you can do sorting using lambda if required.

Related