473,503 Members | 2,098 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Worthwhile to reverse a dictionary

I just started messing with programming and started with Python. Part
of my first project deals with translating numerical values to letters.
I would like to be able to do the reverse as well, letters to numbers,
sort of a table for lookup and a table for reverse lookup. I thought
that a dictionary would be the structure to use- write it once and in a
second instance swap the keys for values and values for keys. However,
reversing a dictionary does not seem to be easily achieved. Am I using
the wrong data structure?

Dec 14 '05 #1
12 3145
ru*********@hotmail.com wrote:
I just started messing with programming and started with Python. Part
of my first project deals with translating numerical values to letters.
I would like to be able to do the reverse as well, letters to numbers,
sort of a table for lookup and a table for reverse lookup. I thought
that a dictionary would be the structure to use- write it once and in a
second instance swap the keys for values and values for keys. However,
reversing a dictionary does not seem to be easily achieved. Am I using
the wrong data structure?


There may be a better solution to your original problem (if you post
more details Im sure there will be plenty of suggestions), but the
following should reverse a dictionary..
testdict = dict(a=1, b=2)
reversedict = dict( (value, key) for key, value in

testdict.iteritems() )

Will McGugan
--
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in
"jvyy*jvyyzpthtna^pbz")
Dec 14 '05 #2
Thanks so much. That seems to have it. This is the sort of thing I
had before:
#!/usr/local/bin/python

# make a short dictionary
d1 = {'A' : '1', 'B' : '2', 'C' : '3'}

for letter in d1.keys(): print letter, '\t', d1[letter]

# make a space between the output of the 2 dictionaries
print '\n'
# reverse the keys and values from the first dictionary
# from this point many things were tried, about the best I achieved was
# getting the last key/value pair as displayed when printing the d1
# it was properly reversed but there was only one pair
d2 = {d1[letter] : letter}

for num in d2.keys(): print num, '\t', d2[num]
This displays
A 1
C 3
B 2

2 B

Dec 14 '05 #3
What is the difference between

" d1 = {'A' : '1', 'B' : '2', 'C' : '3'} "

and

" d1 = dict(A = 1, B = 2, C = 3) " ?

All of the dictionary examples I saw (python.org, aspn.activestate.com,
Learning Python by Lutz, among others) use d={'x' : 'y'}.

Dec 14 '05 #4
ru*********@hotmail.com wrote:
What is the difference between

" d1 = {'A' : '1', 'B' : '2', 'C' : '3'} "

and

" d1 = dict(A = 1, B = 2, C = 3) " ?

All of the dictionary examples I saw (python.org, aspn.activestate.com,
Learning Python by Lutz, among others) use d={'x' : 'y'}.


In the latter case the values are ints, whereas in the former they are
strings. But you probably didn't mean that; indeed it is the case that

d1 = {'A': 1, 'B': 2, 'C': 3}

and

d2 = dict(A=1, B=2, C=3)

are equivalent.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
I do not promise to consider race or religion in my appointments. I
promise only that I will not consider them. -- John F. Kennedy
Dec 14 '05 #5
Thanks. That is exactly what I meant.

In d2, A is not 'A' because it is being set to 1, whereas in d1, using
A instead of 'A' means A is an undeclared variable instead of a string?

Dec 14 '05 #6
Erik Max Francis <ma*@alcyone.com> writes:
ru*********@hotmail.com wrote:
What is the difference between
" d1 = {'A' : '1', 'B' : '2', 'C' : '3'} "
and
" d1 = dict(A = 1, B = 2, C = 3) " ?
All of the dictionary examples I saw (python.org,
aspn.activestate.com,
Learning Python by Lutz, among others) use d={'x' : 'y'}.


In the latter case the values are ints, whereas in the former they are
strings. But you probably didn't mean that; indeed it is the case that
d1 = {'A': 1, 'B': 2, 'C': 3}
and
d2 = dict(A=1, B=2, C=3)
are equivalent.


Not quite:
def f(): .... a = {'a': 1, 'b': 2}
.... b = dict(a = 1, b = 2)
.... dis.dis(f)

2 0 BUILD_MAP 0
3 DUP_TOP
4 LOAD_CONST 1 ('a')
7 LOAD_CONST 2 (1)
10 ROT_THREE
11 STORE_SUBSCR
12 DUP_TOP
13 LOAD_CONST 3 ('b')
16 LOAD_CONST 4 (2)
19 ROT_THREE
20 STORE_SUBSCR
21 STORE_FAST 0 (a)

3 24 LOAD_GLOBAL 1 (dict)
27 LOAD_CONST 1 ('a')
30 LOAD_CONST 2 (1)
33 LOAD_CONST 3 ('b')
36 LOAD_CONST 4 (2)
39 CALL_FUNCTION 512
42 STORE_FAST 1 (b)
45 LOAD_CONST 0 (None)
48 RETURN_VALUE
The first form builds the dict in place, and assigns the result. The
second form invokes the "dict" object on the keyword arguments, which
function then builds the dict. They have the same effect, provided no
one has shadowed the definition of the builtin "dict" function.

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Dec 15 '05 #7
ru*********@hotmail.com wrote:
What is the difference between

" d1 = {'A' : '1', 'B' : '2', 'C' : '3'} "

and

" d1 = dict(A = 1, B = 2, C = 3) " ?

All of the dictionary examples I saw (python.org, aspn.activestate.com,
Learning Python by Lutz, among others) use d={'x' : 'y'}.


The second form is only available in Python 2.3 and newer, so any example that is older
than that will use the first form.

Kent
Dec 15 '05 #8
ru*********@hotmail.com wrote:
I just started messing with programming and started with Python. Part
of my first project deals with translating numerical values to letters.
I would like to be able to do the reverse as well, letters to numbers,
sort of a table for lookup and a table for reverse lookup. I thought
that a dictionary would be the structure to use- write it once and in a
second instance swap the keys for values and values for keys. However,
reversing a dictionary does not seem to be easily achieved. Am I using
the wrong data structure?

This doesn't really answer your question (others have already done this),
but back in the 'ol days we did this:
letters=['a','b','c']
map(lambda x: ord(x)-64, letters)

[1, 2, 3]

This takes advantage of the fact that letters must be stored as
binary integers in ASCII (e.g. 'a' = 65, 'b'=66, etc.). You can
go the other direction with chr(x). Not completely sure about
what you want to accomplish, but this eliminates the need for
the dictionaries.

Larry Bates
Dec 15 '05 #9
The end of what I was trying to do was encode and decode using ITA2
International Telegraph Alphabet 2, more commonly called Baudot. It
uses 5 bit binary but with the use of a shift up or a shift down can
utilize 2 tables of 32- one for letters one for figures.

A better explanation of ITA2 here: http://en.wikipedia.org/wiki/Baudot

It occurred to me that rather than writing for four data dictionaries
(bin to ltrs, bin to figs, figs, to bin, figs to letters), I could just
swap the dictionary key/value pairs around.

It seems that I have more reading to do. I have not gotten to lambda
formations yet.

Dec 15 '05 #10
crc

I assume your talking about building a new dictionary with the key and
value pair switched. I have seen no built in function to do this but I
have found a way to create another dictionary that is the inverse of
the first.

for example you have designed a dictionary such as

a={}
a['one']=1
a['two']=2
a['three']=3
a['four']=4

when your redy to build a revers dictionary you semply do the folowing
b={}
for x in a:
temp_idx=a[x]
b[temp_idx]=x

now you get
{'four': 4, 'three': 3, 'two': 2, 'one': 1}
for a

and

{1: 'one', 2: 'two', 3: 'three', 4: 'four'}
for b
--
crc
Message posted via http://www.exforsys.com for all your training needs.

Jan 4 '06 #11
crc <cr********@no-mx.forums.yourdomain.com.au> writes:
I assume your talking about building a new dictionary with the key and
value pair switched. I have seen no built in function to do this but I
have found a way to create another dictionary that is the inverse of
the first.
Note that you can't reliable "reverse" a dictionary. That's because
you can put anything in a dictionary, but some things can't be used as
keys to a dictionary.
when your redy to build a revers dictionary you semply do the folowing
b={}
for x in a:
temp_idx=a[x]
b[temp_idx]=x


You can do it with a single list comprehension:

b = dict([(x, y) for y, x in a.iteritems()])

<mike
--
Mike Meyer <mw*@mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jan 4 '06 #12
Mike Meyer <mw*@mired.org> wrote:
crc <cr********@no-mx.forums.yourdomain.com.au> writes:
I assume your talking about building a new dictionary with the key and
value pair switched. I have seen no built in function to do this but I
have found a way to create another dictionary that is the inverse of
the first.


Note that you can't reliable "reverse" a dictionary. That's because
you can put anything in a dictionary, but some things can't be used as
keys to a dictionary.


That's reason #1. Reason #2 is that you can have duplicates among a
dict's values, but not among its keys. So, a simply and correctly
reversable dict is one whose values are all hashable and unique -- in
terms of EQUALITY (which is stricter than demanding uniqueness in terms
of IDENTITY), e.g. you can't have both 1 (the integer) and 1.0 (the
float with a 0 fractional part) as values (because they're not distinct
by equality: 1 == 1.0).

If you do have a dict whose hashable values are not guaranteed to be
unique you have several choices as to how to "pseudo-reverse" it (e.g.,
"dropping", among the values in the pseudoreversed dict, all but one of
the keys that map to the same value in the original dict; or, making a
"reversoid" dict whose values are containers of all the keys mapping to
each value in the original dict).

If you have a dict whose values are not guaranteed to be hashable, and
thus can't be keys in the ``sotospeakreverse'' dict, you have to work
even harder, striving to build keys for the latter which may in some
sense (probably one meaningful only to a specific application) "stand
for" the values in the original dict. I remember only one case in a
real-world program of needing anything like that -- the original dict
had "sub"-dicts (mapping strings to numbers) as values, but fortunately
it was acceptable for the application to have frozen sets of (key,
value) pairs "stand for" those subsets in the "reversoid" dict (I sure
did wish at the time I had "frozen dicts", though;-).
Alex
Jan 8 '06 #13

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

Similar topics

5
3486
by: tjland | last post by:
Okay so im working on a very simple encryption method using just loops. Kind of novel i think. Okay so first i set up a list of the alphabet with just every seperate letter, then user is prompted...
35
3701
by: Raymond Hettinger | last post by:
Here is a discussion draft of a potential PEP. The ideas grew out of the discussion on pep-284. Comments are invited. Dart throwing is optional. Raymond Hettinger ...
14
1826
by: Raymond Hettinger | last post by:
Based on the feedback here on comp.lang.python, the pep has been updated: www.python.org/peps/pep-0322.html The key changes are: * reversed() is being preferred to ireverse() as the best...
13
3548
by: Brad Tilley | last post by:
A friend of mine wrote an algorithm that generates strings. He says that it's impossible to figure out exactly how the algorithm works. That may be true, but I think if I had enough sample strings...
6
1885
by: tkpmep | last post by:
I have list of lists of the following form L=, , , ] I want to aggregate these lists, i.e. to reduce L to L=, ] #500 = 100+400, 200=300-100 Here's how I have done it: L.sort() for i in...
8
675
by: xiao zhang yu | last post by:
me was sorry if this question are present before DotNet, no matter VB.Net or C# all they are compiled to IL, and yes, that IL will totally same as "open-sourse", every IL will easy to decompile...
8
7029
by: rh0dium | last post by:
Hi all, I have a dict which looks like this.. dict={'130nm': {'umc': }, '180nm': {'chartered': , 'tsmc': }, '250nm': {'umc': , 'tsmc': } }
41
3336
by: rick | last post by:
Why can't Python have a reverse() function/method like Ruby? Python: x = 'a_string' # Reverse the string print x Ruby: x = 'a_string' # Reverse the string
40
36431
by: KG | last post by:
Could any one tell me how to reverse the bits in an interger?
0
7204
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7342
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...
1
6998
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...
0
7464
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...
0
5586
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,...
0
4680
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...
0
3162
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1516
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
391
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.