Question:
Python programming: dictionaries?
Frost00
2012-04-08 06:56:46 UTC
Hi, Im trying to print a value from a dictionary, so I use:
nameofdict[key] e.g. myDict['Blue']

However, this prints out the value in braces:
['Sky']

My question is then, how do I print out the value without the braces and quotes? N.B The value may also be more than one item, e.g. ['Sky', 811]
Five answers:
2012-04-08 07:32:06 UTC
Blue = myDict.get("Blue", [])

if len(Blue) > 0:

Sky = Blue[0]

print Sky



Edit: You could try:



Blue = myDict.get("Blue", [])

if len(Blue) > 0:

print "".join(Blue[0])
?
2012-04-08 07:01:30 UTC
That is just how python works it gives it to you in [ ] because that's how dictionaries store things [key, value] pairs and it just gives you the value. I am not super sure but it looks like its returning an array to me you should be able to loop through and set each index and print the values without quotes



Edit: How are you running this IDE, CL interpretur etc...? Because I ran it through the linux terminal and get the value with no [ ] it may be possible that you are somehow creating a list or array as the value and that is why your getting that as a result if your use the syntax dictName = {'key1': val1, 'key2': val2} you shouldn't experience that issue also you can add things to an existing dictionary using the syntax dictName['key3'] = val3 (as a heads up)
husoski
2012-04-08 07:33:47 UTC
['Sky'] is a list of 1 element (the string 'Sky') and you only get ['Sky'] out of the dictionary if you put it in as a list in the first place. Fire up Idle, and try this: (Pasted from Idle 2.7.2)



Python 2.7.2 (default, Jun 12 2011, 15:08:59) ... yada yada

>>> d = { 'Blue' : 'Sky', 'Answer' : 42, 'blue' : ['Sky'] }

>>> d['Blue']

'Sky'

>>> d['blue']

['Sky']

>>>



The brackets only come out when you put the item in as a list.



Dictionaries are not your problem. Lists are. The brackets (and quotes) are part of the display format for a list. If you want some other format, you have to write code. Try:

def listfmt(mylist):

... result = ''

... sep = ''

... for e in mylist:

... ... result = result + sep + str(e)

... ... sep = ', '

... return result



Now print( listfmt( [ 1, 3, 'five' ] ) ) and see what you get. (Those dots are for visual indentation, by the way.)
2012-04-08 07:00:33 UTC
Sound like you need to use the dereference operator. I'm not sure how to help further.
?
2016-11-29 07:56:13 UTC
hi, one way is to apply raw_input() particularly of enter() get entry to = raw_input("enter a great determination: ") if get entry to.isdigit(): # convert this to a great determination, and do in spite of you elect with the huge type num = int(get entry to) else: print "Invalid get entry to"


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...