ClamSnorkel
ClamSnorkel

Reputation: 3

Combining Key-Value Pairs from two Dictionaries

I have two dictionaries that I would like to correlate key-value pairs.

For example:

a_dict = [a:1, b:1, c:2, d:3]

b_dict = [z:1, xy:2, gf:4, fd:4]

How could I go about combining them to print as follows:

a, 1, z, 1

b, 1, xy, 2

c, 2, gf, 4

d, 3, fd, 4

Logic I used to get the key-value pairs for the dicts:

a_dict = dict()
for i in file:
    a = i.split("|")[3]
    if a in a_dict.keys():
        a_dict[a] += 1
    else:
        a_dict[a] = 1

for a in a_dict.keys():
    b_dict = dict()
    for i in file:
        if a not in i:
            continue
        else:
            b = i.split("|")[5]
            if b in b_dict.keys():
                b_dict[b] += 1
            else:
                b_dict[b] = 1

Upvotes: 0

Views: 138

Answers (2)

Matt Messersmith
Matt Messersmith

Reputation: 13747

First, as the comments have said, dictionaries are unordered. If you want to combine the keys where order matters (i.e. the first key you inserted in a_dict should match with the first key you inserted in b_dict), you need to use an OrderedDict. So, you would need to change a_dict and b_dict to be OrderedDict objects when you read in from your file(s). Here's an example of how to print the keys how you're asking:

from collections import OrderedDict

a_dict = OrderedDict()
b_dict = OrderedDict()

a_dict["a"] = 1
a_dict["b"] = 1
a_dict["c"] = 2
a_dict["d"] = 3

b_dict["z"] = 1
b_dict["xy"] = 2
b_dict["gf"] = 4
b_dict["fd"] = 4

for a_key, b_key in zip(a_dict, b_dict):
    print a_key, ", ", a_dict[a_key], ", ", b_key, ", ", b_dict[b_key]

outputs:

a ,  1 ,  z ,  1
b ,  1 ,  xy ,  2
c ,  2 ,  gf ,  4
d ,  3 ,  fd ,  4

Observe that this will not always work with normal dictionaries (although it may depending on the keys). Change the above answer to initialize a_dict and b_dict like so:

a_dict = dict()
b_dict = dict()

and you will probably see a different output where the keys don't match up. My console gives me:

a ,  1 ,  xy ,  2
c ,  2 ,  gf ,  4
b ,  1 ,  z ,  1
d ,  3 ,  fd ,  4

Moral of the story: don't use a dict when order matters. They are simply key value stores, the order of their keys is arbitrary.

Upvotes: 1

audittxl
audittxl

Reputation: 41

Step 1) Convert them into a list.

dict1=dict1.items()
dict2=dict2.items()

Step 2) Loop through them as so (assuming both dict (now lists) are the same size):

for i in range(len(dict1)):
>print(dict1[i][0],dict1[i][1],dict2[i][0],
dict1[i][1])

I apologise for the formatting since i am doing this on my phone.

NB > = tab

Edit: i cannot verify if this works since i am not sitting in front of my computer.

Upvotes: 0

Related Questions