473,320 Members | 1,950 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

simple question about dictionaries

hi, i am new to python, so i've a really simple question about
dictionaries.
if i have a dictionary and I make have an input after it (to input
numbers) can i get the key of value that was in input?

somehting like this:
dict = { "key1"=100,"key2"=200,"key3"=300}
a = input()
print 'the key of inputted value is', dict['a']

this syntax of course is wrong, but i hope you got the point..

thanks in advance!

Jul 21 '08 #1
6 946
Sounds like a school assignment. Find the answer yourself here:
http://diveintopython.org/toc/index.html

You'll learn a lot more in the process.

2B
Jul 21 '08 #2
On Jul 21, 7:35*am, skazhy <ska...@gmail.comwrote:
hi, i am new to python, so i've a really simple question about
dictionaries.
if i have a dictionary and I make have an input after it (to input
numbers) can i get the key of value that was in input?

somehting like this:
dict = { "key1"=100,"key2"=200,"key3"=300}
a = input()
print 'the key of inputted value is', dict['a']

this syntax of course is wrong, but i hope you got the point..

thanks in advance!
I don't think there is a built-in that retrieves dict keys by value,
but if the dictionary were small enough, you could search the list of
key/value pairs returned by dict.items(). You can also iterate
through all pairs with dict.iteritems(), which returns an iterator.
Something like:

def key_by_value(dct, val):
for k, v in dct.iteritems():
if v == val:
return v
throw KeyError('%s not found' % str(val))

Jul 21 '08 #3
skazhy wrote:
hi, i am new to python, so i've a really simple question about
dictionaries.
if i have a dictionary and I make have an input after it (to input
numbers) can i get the key of value that was in input?
A dictionary contains (key, value) pairs, and is optimized for quickly
finding the value in a pair, if given the key.
somehting like this:
dict = { "key1"=100,"key2"=200,"key3"=300}
dict() is a built-in function; you're free to reuse the names of such
functions as variable names in Python, but if you do, you won't be able
to use those functions in that part of your program. And in this case,
the dict() built-in might be useful (see below):
a = input()
print 'the key of inputted value is', dict['a']

this syntax of course is wrong, but i hope you got the point..
Assuming that you want the *key* in Python's sense, for a given value,
you can either loop over the dictionary (called D below):

for k, v in D.items():
if v == a:
print 'the key of inputted value is', v
break
else:
print "not found"

or create an reverse mapping and use that (you only have to do this
every time the dictionary changes, of course), e.g.

reverse_D = dict((D[k], k) for k in D)

a = input()
print "the key for value", a, "is", reverse_D[a]

(this doesn't work if you call your dictionary "dict", obviously.)

</F>

Jul 21 '08 #4
Jeff wrote:
throw KeyError('%s not found' % str(val))
"throw"? and shouldn't that be a ValueError? ;-)

</F>

Jul 21 '08 #5
On Jul 21, 8:14*am, Fredrik Lundh <fred...@pythonware.comwrote:
Jeff wrote:
* throw KeyError('%s not found' % str(val))

"throw"? *and shouldn't that be a ValueError? ;-)

</F>
Whoops. Been working in too many different languages at the same
time :).
Jul 22 '08 #6
On Jul 21, 8:14*am, Fredrik Lundh <fred...@pythonware.comwrote:
Jeff wrote:
* throw KeyError('%s not found' % str(val))

"throw"? *and shouldn't that be a ValueError? ;-)

</F>
Whoops. Been working in too many different languages at the same
time :).
Jul 22 '08 #7

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

Similar topics

7
by: Markus Joschko | last post by:
Hi all, I' new to python programming but a longtime java programmer. Is there an API documentation like the javadoc API from java? I'm want to know all methods I can use on dictionaries. Where...
13
by: Paulo Pinto | last post by:
Hi, does anyone know of a Python package that is able to load XML like the XML::Simple Perl package does? For those that don't know it, this package maps the XML file to a dictionary.
4
by: Thomas Philips | last post by:
I'm teaching myself python and in the course of playing around with dictionaries, I tried to create the following trivial dictionary {1:'one', 2:'two'} So I entered >>> dict(1='one',2='two')...
8
by: Frohnhofer, James | last post by:
My initial problem was to initialize a bunch of dictionaries at the start of a function. I did not want to do def fn(): a = {} b = {} c = {} . . . z = {}
19
by: gaudetteje | last post by:
I've been searching high and low for a way to simply convert a small XML configuration file to Python data structures. I came across gnosis XML tools, but need a built-in option for doing...
3
by: Faisal Alquaddoomi | last post by:
Hello, I'm having a bit of trouble isolating my scripts from each other in my embedded Python interpreter, so that their global namespaces don't get all entangled. I've had some luck with...
8
by: placid | last post by:
Hi all, Just wondering if anyone knows how to pop up the dialog that windows pops up when copying/moving/deleting files from one directory to another, in python ? Cheers
9
by: Jonathan Fine | last post by:
Hello I want to serialise a dictionary, whose keys and values are ordinary strings (i.e. a sequence of bytes). I can of course use pickle, but it has two big faults for me. 1. It should not...
1
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...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...

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.