473,666 Members | 2,039 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

join dictionaries using keys from one & values

I'm still learning python so this might be a crazy question but I
thought I would ask anyway. Can anyone tell me if it is possible to
join two dictionaries together to create a new dictionary using the
keys from the old dictionaries?

The keys in the new dictionary would be the keys from the old
dictionary one (dict1) and the values in the new dictionary would be
the keys from the old dictionary two (dict2). The keys would be joined
by matching the values from dict1 and dict2. The keys in each
dictionary are unique.

dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}

dict2 = {5.01:'bbb', 6.01:'ccc', 7.01:'aaa'}

dict3 = {1 : 5.01, 3 : 6.01, 2 : 7.01}

I looked at "update" but I don't think it's what I'm looking for.

Thanks,

Greg

Dec 6 '05 #1
7 7901
ProvoWallis wrote:
I'm still learning python so this might be a crazy question but I
thought I would ask anyway. Can anyone tell me if it is possible to
join two dictionaries together to create a new dictionary using the
keys from the old dictionaries?


There is no builtin method. The usual way is to just wrap a class
around two dictionaries, one for mapping keys to values and the other
for mapping values back to keys.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
Yes I'm / Learning from falling / Hard lessons
-- Lamya
Dec 6 '05 #2

ProvoWallis wrote:
I'm still learning python so this might be a crazy question but I
thought I would ask anyway. Can anyone tell me if it is possible to
join two dictionaries together to create a new dictionary using the
keys from the old dictionaries?

The keys in the new dictionary would be the keys from the old
dictionary one (dict1) and the values in the new dictionary would be
the keys from the old dictionary two (dict2). The keys would be joined
by matching the values from dict1 and dict2. The keys in each
dictionary are unique.

dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}

dict2 = {5.01:'bbb', 6.01:'ccc', 7.01:'aaa'}

dict3 = {1 : 5.01, 3 : 6.01, 2 : 7.01}

I looked at "update" but I don't think it's what I'm looking for.

Thanks,

If you can be sure that the value is hashable, I think you can just
invert one of the dict(key/value flipped) and a for loop to create the
new dict

dict2x = dict( ((dict2[k], k) for k in dict2.iterkeys( )))
dict3 = dict(((k, dict2x[v]) for k,v in dict1.iteritems ()))

This doesn't handle the case where v is in dict1 but not in dict2, it
can be filtered out though.

Dec 6 '05 #3
Thanks so much. I never would have been able to figure this out on my
own.

def dictionary_join (one, two):

dict2x = dict( ((dict2[k], k) for k in dict2.iterkeys( )))
dict3 = dict(((k, dict2x[v]) for k,v in dict1.iteritems ()))
print dict3

dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}

dict2 = {'5.01':'bbb', '6.01':'ccc', '7.01':'aaa'}

dictionary_join (dict1, dict2)

Dec 6 '05 #4

ProvoWallis wrote:
Thanks so much. I never would have been able to figure this out on my
own.

def dictionary_join (one, two):

dict2x = dict( ((dict2[k], k) for k in dict2.iterkeys( )))
dict3 = dict(((k, dict2x[v]) for k,v in dict1.iteritems ()))
print dict3

dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}

dict2 = {'5.01':'bbb', '6.01':'ccc', '7.01':'aaa'}

dictionary_join (dict1, dict2)


You might want to make a working function.

def join_dicts(d1,d 2):
temp = dict(((d2[k], k) for k in d2.iterkeys()))
joined = dict(((k, temp[v]) for k,v in d1.iteritems()) )
return joined

Dec 6 '05 #5
ProvoWallis <gs**********@e arthlink.net> wrote:
...
The keys in the new dictionary would be the keys from the old
dictionary one (dict1) and the values in the new dictionary would be
the keys from the old dictionary two (dict2). The keys would be joined
by matching the values from dict1 and dict2. The keys in each
dictionary are unique.
....but are the VALUES unique...? That's the crucial issue and you don't
mention anything about it.
dict1 = {1:'bbb', 2:'aaa', 3:'ccc'}

dict2 = {5.01:'bbb', 6.01:'ccc', 7.01:'aaa'}

dict3 = {1 : 5.01, 3 : 6.01, 2 : 7.01}


But what if in dict1 both keys 2 and 3 had a corresponding value of
'ccc' -- what would you want as a result then? What if key 1 had a
corresponding value of 'ddd' -- not a value in dict2; what would you
want THEN? Without a more complete specification, it's impossible to
tell, and one key Python principle is "in the face of ambiguity, refuse
the temptation to guess".

If values are assured to be unique, and the sets of values of the two
dictionaries are assured to be identical, then the suggestion (already
given in another post) to invert dict2 is a good idea, i.e., as a
function:

def PWmerge(d1, d2):
invd = dict((v2, k2) for k2, v2 in d2.iteritems())
return dict((k1,invd[v1]) for k1,v1 in d1.iteritems())

but without all of the above assurances, different tweaks may be needed
depending on what exactly you want to happen in the several "anomalous"
cases.
Alex
Dec 6 '05 #6
Super simple:

dict3 = {}
for k1 in dict1.keys():
for k2 in dict2.keys():
if dict1.get(k1) == dict2[k2]:
dict3[k1] = k2

works in all cases and can be simplified to an iterated dictionary in
python 2.4

Dec 6 '05 #7
Thanks again. This is very helpful.

Dec 7 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2368
by: Shivram U | last post by:
Hi, I want to store dictionaries on disk. I had a look at a few modules like bsddb, shelve etc. However would it be possible for me to do the following hash = where the key is an int and not a string bsddb requires that both the key,value are string. shelve does support values being object but not the keys. Is there any
210
10441
by: Christoph Zwerschke | last post by:
This is probably a FAQ, but I dare to ask it nevertheless since I haven't found a satisfying answer yet: Why isn't there an "ordered dictionary" class at least in the standard list? Time and again I am missing that feature. Maybe there is something wrong with my programming style, but I rather think it is generally useful. I fully agree with the following posting where somebody complains why so very basic and useful things are not part...
9
1342
by: javuchi | last post by:
I've been searching thru the library documentation, and this is the best code I can produce for this alogorithm: I'd like to return a dictionary which is a copy of 'another' dictionary whoes values are bigger than 'x' and has the keys 'keys': def my_search (another, keys, x): temp = another.fromkeys(keys) return dict( for k in temp.keys() for v in temp.values() if v>=x])
15
1355
by: pretoriano_2001 | last post by:
Hello: I have next dictionaries: a={'a':0, 'b':1, 'c':2, 'd':3} b={'a':0, 'c':1, 'd':2, 'e':3} I want to put in a new dictionary named c all the keys that are in b and re-sequence the values. The result I want is: c={'a':0, 'c':1, 'd':2} How can I do this with one line of instruction? I attempted the next but the output is not the expected:
16
1622
by: IamIan | last post by:
Hello, I'm writing a simple FTP log parser that sums file sizes as it runs. I have a yearTotals dictionary with year keys and the monthTotals dictionary as its values. The monthTotals dictionary has month keys and file size values. The script works except the results are written for all years, rather than just one year. I'm thinking there's an error in the way I set my dictionaries up or reference them... import glob, traceback
4
1807
by: kdt | last post by:
Hi Trying to create a function that takes two dictionaries, and deletes key:values that are common in both dictionaries. So far I have the following; but I can only delete values in one dictionary as I am iterating over the other. Or is there a way to rename keys in dictionaries? Thanks in advance. def filterByKey(dict1, dict2): ''' Takes two dictionaries and deletes matching records; Dict1 is the main dictionary; ...
9
1258
by: Brandon | last post by:
Hi all, I am not altogether experienced in Python, but I haven't been able to find a good example of the syntax that I'm looking for in any tutorial that I've seen. Hope somebody can point me in the right direction. This should be pretty simple: I have two dictionaries, foo and bar. I am certain that all keys in bar belong to foo as well, but I also know that not all keys in foo exist in bar. All the keys in both foo and bar are...
1
165
by: Edwin.Madari | last post by:
by the way, iterating over bar will throw KeyError if that key does not exist in foo. to see that in action, simply set another key in bar after copy.deepcopy stmt in this example.. bar = 0 and re-run.... fun learning with python... Edwin -----Original Message----- From: Madari, Edwin Sent: Thursday, August 14, 2008 9:24 PM
14
1809
by: cnb | last post by:
Are dictionaries the same as hashtables?
0
8356
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8783
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8552
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8640
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7387
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6198
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5666
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4198
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4369
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.