how to create a dictionary out of 2 other dictionaries

This is the place for queries that don't fit in any of the other categories.

how to create a dictionary out of 2 other dictionaries

Postby eedodge3 » Wed Aug 14, 2013 9:37 pm

how do i create a dictionary out of 2 other dictionaries. I want to sum all items in a tuple.

if i have these:
Code: Select all
dict1={'aaa':(2,2,2),'bbb':(1,2,3)}
dict2={'aaa':(1,2,3),'bbb':(2,4,6)}

i want to make something like this:
Code: Select all
dict2={'aaa':(3,4,5),'bbb':(3,6,9)}

i thought about doing something like this:
Code: Select all
for i to range(3):
    x=dict1['aaa'][i] + dict2['aaa'][i]
    y=y + "," + str(x)
z={'aaa': y}
dict2.update(z)

but i couldn't make it work.

any suggestion? is there a more efficient way to do this? thanks in advance
Last edited by Mekire on Wed Aug 14, 2013 11:35 pm, edited 1 time in total.
Reason: Added code tags.
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm

Re: how to create a dictionary out of 2 other dictionaries

Postby eedodge3 » Wed Aug 14, 2013 11:39 pm

i was able to make this code work but still looking for an alternative/simpler way. this is because the number of source dictionaries can go up to about 20 so my code will get very long.

source dictionaries: (i.e. dict1, dict2,......dict20)
desired output: sum_dict

Code: Select all
dict3={}
mylist=['aaa','bbb']
   for c in mylist:     
        for i in reversed(range(3)):
            m=int(dict1[c][i])
            n=int(dict2[c][i])
            x=m+n
            y=str(x) + "," + y
        z={c: "(" + "".join(y) + ")"}
        dict3.update(z)
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm

Re: how to create a dictionary out of 2 other dictionaries

Postby Yoriz » Wed Aug 14, 2013 11:56 pm

Something like this i guess.
Code: Select all
dict1 = {'aaa': (2, 2, 2), 'bbb': (1, 2, 3)}
dict2 = {'aaa': (1, 2, 3), 'bbb': (2, 4, 6)}

for key in dict2.keys():
    newitems = []
    for item1, item2 in zip(dict1[key], dict2[key]):
        newitems.append(item1 + item2)
    dict2[key] = tuple(newitems)

print dict2

Output
Code: Select all
{'aaa': (3, 4, 5), 'bbb': (3, 6, 9)}
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 565
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: how to create a dictionary out of 2 other dictionaries

Postby Mekire » Thu Aug 15, 2013 12:04 am

Smart-ass one-liner:
Code: Select all
new = {key:map(sum,zip(dict1[key],dict2[key])) for key in dict1 if key in dict2}
print(new)
Code: Select all
{'aaa': [3, 4, 5], 'bbb': [3, 6, 9]}

-Mek
User avatar
Mekire
 
Posts: 814
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: how to create a dictionary out of 2 other dictionaries

Postby micseydel » Thu Aug 15, 2013 12:08 am

Code: Select all
for items in zip(*(d[key] for d in dictionaries)):
        newitems.append(sum(items))

This will scale well to an arbitrary number of dictionaries.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 928
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: how to create a dictionary out of 2 other dictionaries

Postby Yoriz » Thu Aug 15, 2013 12:39 am

My probably terrible one liner for any number of dicts
Code: Select all
dict1 = {'aaa': (2, 2, 2), 'bbb': (1, 2, 3)}
dict2 = {'aaa': (1, 2, 3), 'bbb': (2, 4, 6)}
dict3 = {'aaa': (5, 6, 7), 'bbb': (3, 7, 9)}

dicts = (dict1, dict2, dict3)

new_dict = {key: tuple(map(sum, zip(*[items[key] for items in dicts])))
            for key in dicts[0].keys()}

print new_dict

Output
Code: Select all
{'aaa': (8, 10, 12), 'bbb': (6, 13, 18)}
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 565
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: how to create a dictionary out of 2 other dictionaries

Postby eedodge3 » Thu Aug 15, 2013 12:43 am

thanks for all the replies.

i have another question. i create the dictionaries from multiple files (one dictionary/file). each file has a sequencial file name. my question is, how do i create each dictionary and name it so that i can reference to it later in a loop. something like i=0, dict + str(i) becomes dict0. in short i want it dynamic. files can be from 10 to 20.

Code: Select all
for i in range(20):
   d={}
    with open(rawdir + i, 'r') as f:
        for line in f:
             x=line.strip().split(" ")
             y=x[0]
            z=z=tuple(x[1:])
            d[y]=z
        dict +str(i) = d  ##########this doesn't work

print dict0   #####error

####to use it on yoriz's code#####

for key in dict2.keys():
    newitems = []
    for item1, item2 in zip(dict1[key], dict2[key]...............dict20[key]):
        newitems.append(int(item1) + int(item2))
    dict2[key] = tuple(newitems)
   
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm

Re: how to create a dictionary out of 2 other dictionaries

Postby Yoriz » Thu Aug 15, 2013 12:46 am

Append the dictionarys to a list.
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 565
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: how to create a dictionary out of 2 other dictionaries

Postby eedodge3 » Thu Aug 15, 2013 1:12 am

hi yoriz i tried your suggestion but i got an error. could you check please?
Code: Select all

dicts=[]
for i in range(2)
    with open(rawdir + i, 'r') as f:
        for line in f:
            x=line.strip().split(" ")
            y=x[0]
            z=tuple(x[1:])
            d[y]=z
        dicts.append(d)
print dicts ###############works up to here
new_dict = {key: tuple(map(sum, zip(*[items[key] for items in dicts]))) for key in dicts[0].keys()}
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm

Re: how to create a dictionary out of 2 other dictionaries

Postby micseydel » Thu Aug 15, 2013 1:33 am

Your third line should be failing with a very helpful error message, you shouldn't be getting to the line you indicate as the code reaching. Also, never post in a forum that you're "getting an error" without providing the entire error message verbatim. And here, I recommend putting that error in code tags because it has indentation that makes it easier to read.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 928
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: how to create a dictionary out of 2 other dictionaries

Postby eedodge3 » Thu Aug 15, 2013 2:53 am

sorry i just copied and pasted parts of the code. like i said i only got the error once the script reached the line below.

File "test.py", line 46
new_dict = {key: tuple(map(sum, zip(*[items[key] for items in dicts]))) for key in dicts[0].keys()}
^
SyntaxError: invalid syntax
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm

Re: how to create a dictionary out of 2 other dictionaries

Postby Mekire » Thu Aug 15, 2013 3:02 am

Quite often when you get a SyntaxError the problem is on the previous line. Look there.
-Mek
User avatar
Mekire
 
Posts: 814
Joined: Thu Feb 07, 2013 11:33 pm
Location: Amakusa, Japan

Re: how to create a dictionary out of 2 other dictionaries

Postby micseydel » Thu Aug 15, 2013 3:10 am

If you get a syntax error, your code isn't running yet. It's different than errors people usually see. (I don't expect you to know this already, but it's something you should know after right now).

The most common cause of syntax errors for newbs who can't figure it out is a forgotten closing braces/paren/bracket. Since we can tell from the error you posted that you're not showing us your whole code, we can't really help. You shouldn't post 40+ lines of code though. Usually, problems can be reproduces in 10 or less lines, and you should post code that produces your same problem by hard coding values that previous lines create.
Join the #python-forum IRC channel on irc.freenode.net!
User avatar
micseydel
 
Posts: 928
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: how to create a dictionary out of 2 other dictionaries

Postby eedodge3 » Thu Aug 15, 2013 4:52 pm

okay i gave up on the one liner. here's what works for me. thanks for all the comments.

Code: Select all
    for key in dicts[0].keys():
        newitems=[]
        for items in zip(*(d[key] for d in dicts)):
             newitems.append(sum(items))
        dict2[key] = tuple(newitems)
eedodge3
 
Posts: 17
Joined: Mon Jul 29, 2013 5:59 pm


Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot] and 4 guests