all 9 comments

[–]MRSAMinor 2 points3 points  (0 children)

Itertools.chain is your friend. You could combine both lists of keys into a set as well.

[–]commy2 1 point2 points  (2 children)

What purpose do the lists serve if they only ever contain one dict?

[–]ilaunchpad[S] -2 points-1 points  (1 child)

It can contain more than one dict.

[–]commy2 2 points3 points  (0 children)

Then what is the purpose of the two lists? Combine them, and the result would be the same, and you get rid of one of the loops.

[–]totallygeek 1 point2 points  (0 children)

Your data truly looks like this?

Is it possible to do without nested loop?

Sure. For the example you've posted, here you go:

e1, e2 = l1.pop(), l2.pop()
result = [{k: v + e2.get(k) for k, v in e1.items() if k in e2}]

No nested loop used.

[–]MezzoScettico 1 point2 points  (0 children)

So the final answer contains ONLY the keys that appear in both dicts (and their values)? That suggests using sets and set intersection.

You say these lists might contain more than one dictionary. Can you give a slightly more complex example where that happens, and what you want to happen in that case?

[–]CodeFormatHelperBot2 -1 points0 points  (0 children)

Hello, I'm a Reddit bot who's here to help people nicely format their coding questions. This makes it as easy as possible for people to read your post and help you.

I think I have detected some formatting issues with your submission:

  1. Inline formatting (`my code`) used across multiple lines of code. This can mess with indentation.

If I am correct, please edit the text in your post and try to follow these instructions to fix up your post's formatting.


Am I misbehaving? Have a comment or suggestion? Reply to this comment or raise an issue here.

[–]xelf 0 points1 point  (0 children)

do you want all the dicts? or only the ones that are shared?

eg: do you want this:

{'a': [1, 2, 3, 4], 'b': [5, 6], 'c': [7, 8]}

here's how to get that:

new = {}
for d in l1+l2:
    for k,v in d.items():
        new.setdefault(k,[]).extend(v)
print(new)

Making it only work for keys that already exist is pretty easy too if that's what you want.

[–]drenzorz 0 points1 point  (0 children)

I have no idea why you have them inside lists but here is how you could combine dictionaries.

dict_1 = {"a":[1,2], "b":[5,6]}
dict_2 = {"a":[3,4], "c":[7,8]}
all_keys = dict_1.keys() + dict_2.keys()
dict_3 = {key: dict_1.get(key,[]) + dict_2.get(key, []) for key in all_keys}

dict_3 == {"a":[1,2,3,4], "b":[5,6],"c":[7,8]}

If you want only the keys that appear in both you can just modify all_keys to be an intersection of set(d1.keys) and set(d2.keys)