PRK PRK - 3 years ago 199
Python Question

How to iterate over two dictionaries and save them in a list in python

I am trying to iterate over two dictionaries

d = {'d': 2, 'c': 6, 'a': 1, 'b': 3}
and
d2 = {'j': 9, 'b': 5, 'a': 2, 'k': 10}
. It should store values like
[[key1, value1 value2], [key1, value1, value2], [key2, value1, value2]...]

First, trying to store
d
values in a
my_list
as
my_list = [d[keys], d[values], 0]
.

My code is as below,

my_list = []
for i, j in d.items():
if i in my_list:
print(i, "is in list")
else:
my_list.append([i,j,0])

output: my_list = [['d', 2, 0], ['c', 6, 0], ['a', 1, 0], ['b', 3, 0]]


Then, iterate over
d2
and if key of
d2
exists in
my_list
then replace
0
with
d2[values]
else add it to
my_list
like
[d2[keys], 0, d2[values]]
.

When I check
'd' in my_list
, it gives me
False
and
True
for
'd' in my_list[0][0]
.

So, to get
my_list[0][0]
position, I've used another
for loop
something like,

for k in range(len(d2)):
for i, j in d2.items():
if i in my_list[k][0]:
my_list[k][2] = d2[j]
else:
my_list.append([i,0,j])


which gives me error,

Traceback (most recent call last):
File "<pyshell#505>", line 4, in <module>
my_list[k][2] = d2[j]
KeyError: 2


What I am missing here?

Can anyone please tell me how to add keys and their values without duplicating in a list?

Thank you

Answer Source

You can form the result in three steps. First create a list containing keys that exists on both dicts. Then add keys that exist only first one and finally add the keys that are only on second dict.

d = {'d': 2, 'c': 6, 'a': 1, 'b': 3}
d2 = {'d': 9, 'b': 5, 'a': 2, 'k': 10}

result = [[k, d[k], d2[k]] for k in d.keys() & d2.keys()]
result.extend([k, d[k], 0] for k in d if k not in d2)
result.extend([k, 0, d2[k]] for k in d2 if k not in d)

print(result)

Output:

[['b', 3, 5], ['d', 2, 9], ['a', 1, 2], ['c', 6, 0], ['k', 0, 10]]

You could do this with union and dict.get as well:

>>> d = {'d': 2, 'c': 6, 'a': 1, 'b': 3}
>>> d2 = {'d': 9, 'b': 5, 'a': 2, 'k': 10}
>>> [[k, d.get(k, 0), d2.get(k, 0)] for k in d.keys() | d2.keys()]
[['k', 0, 10], ['c', 6, 0], ['d', 2, 9], ['a', 1, 2], ['b', 3, 5]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download