Jack Randall
Jack Randall

Reputation: 3

Creating an organized dictionary by combining multiple other dictionaries

I am trying to create a master dictionary in python through the process of pulling values form 3 separate dictionaries. The 3 dictionaries look something like this:

X = {'0':[1, 3, 4, 5], '.001':[2, 4, 6, 7]} 
Y = {'0':[5, 6, 9, 2], '.001':[2, 6, 8, 4]} 
Z = {'0':[3, 6, 8, 9], '.001':[3, 1, 5, 8]} 

I would like to be able to combine these dictionaries into a single master dictionary that groups the first value from X, Y, and Z, the second value from X, Y, and Z and so forth.The final dictionary would look something like this:

Final = {'0':[1, 5, 3], [3, 6, 6], [4, 9, 8], [5, 2, 9], '.001':[2, 2, 3]..... 

and so forth. I believe I need to use a for loop for this but am unsure. Any help is greatly appreciated.

Here is the code i have thus far. All of the individual dictionaries get created correctly but the final one does not.

Xcoord = {}
time = []
with open ('Nodal_QuardnetsX2.csv', 'r') as f:
    f.readline() # Skips first line
    for line in f:
        values = [s.strip()for s in line.split(',')]
        Xcoord[values[0]] = map(float, values[1:])
        time.append(values[0])
        print time
Ycoord = {}
with open ('Nodal_QuardnetsY2.csv', 'r') as f:

    f.readline() # Skips first line
    for line in f:
        values = [s.strip()for s in line.split(',')]
        Ycoord[values[0]] = map(float, values[1:])

Zcoord = {}
with open ('Nodal_QuardnetsZ2.csv', 'r') as f:
    f.readline() # Skips first line
    for line in f:
        values = [s.strip()for s in line.split(',')]
        Zcoord[values[0]] = map(float, values[1:])

counter = 0
k = len(Xcoord)
for time in range(k):
    CoordCombo[time] = Xcoord[counter], Ycoord[counter], Zcoord[counter]
    counter = counter + 1

Upvotes: 0

Views: 107

Answers (3)

SaulTheBear
SaulTheBear

Reputation: 23

Here are two functions to create a "master dictionary" that only includes values that are common to all input dictionaries. The X,Y,Z example you give doesn't have any values common to all three dictionaries, so you end up with an empty dictionary.

X = {'0':[1, 3, 4, 5], '.001':[2, 4, 6, 7]} 
Y = {'0':[5, 6, 9, 2], '.001':[2, 6, 8, 4]} 
Z = {'0':[3, 6, 8, 9], '.001':[3, 1, 5, 8]}

dictionaries = [X,Y,Z]

def compare(d1, d2):
    d3 = {}
    for key in d1:
        for v in d1[key]:
            if v in d2[key]:
                if key in d3:
                    d3[key].append(v)
                else: d3[key] = [v,]

    return d3

def createMaster(dictionaries):
    length = len(dictionaries)

    if length == 1:
        return dictionaries[0]

    d1 = dictionaries.pop()
    d2 = dictionaries.pop()
    d3 = compare(d1, d2)

    if length == 2: 
        return = d3

    else: 
        dictionaries.append(d3)
        return createMaster(dictionaries)

Upvotes: 1

Finn Årup Nielsen
Finn Årup Nielsen

Reputation: 6726

Yes as @user3885927 notes your syntax is wrong.

With the result as a dict of list of tuples you can do:

>>> {key: zip(X[key], Y[key], Z[key]) for key in X.keys()}
{'0': [(1, 5, 3), (3, 6, 6), (4, 9, 8), (5, 2, 9)], '.001': [(2, 2, 3), (4, 6, 1), (6, 8, 5), (7, 4, 8)]}

Or as a dict of tuples of lists:

>>> {key: tuple([[x, y, z] for x, y, z in zip(X[key], Y[key], Z[key])]) for key in X.keys()}
{'0': ([1, 5, 3], [3, 6, 6], [4, 9, 8], [5, 2, 9]), '.001': ([2, 2, 3], [4, 6, 1], [6, 8, 5], [7, 4, 8])}

Upvotes: 0

user3885927
user3885927

Reputation: 3503

@JackRandall, they syntax of your Final dictionary is not correct. I suggest you read https://docs.python.org/2/tutorial/datastructures.html#dictionaries to get an idea of dictionaries. You probably want your final dictionary look like this instead:

Final = {'0':[[1, 5, 3], [3, 6, 6], [4, 9, 8], [5, 2, 9]], '.001':[[2, 2, 3].....]}

And to get started you can loop through your keys in X and then using the key access elements of Y and Z and append all of them to array of Final['key']. This should get you started and I can answer more questions.

Here is an update based on your comments: If the key doesn't exist in X it will insert None

X = {'0':[1, 3, 4, 5], '.001':[2, 4, 6, 7], 'XonlyKey':[1,1,1,1,]} 
Y = {'0':[5, 6, 9, 2], '.001':[2, 6, 8, 4]} 
Z = {'0':[3, 6, 8, 9], '.001':[3, 1, 5, 8]}
Final={}
for key, value in X.iteritems():
    tempArray=[value]
    for tempDict in (Y,Z):
        if key in tempDict:
            tempArray.append(tempDict[key])
        else:
            tempArray.append(None)
    Final[key]=tempArray

Upvotes: 1

Related Questions