views:

188

answers:

5

I have a dictionary with one key and two values and I want to set each value to a separate variable.

d= {'key' : ('value1, value2'), 'key2' : ('value3, value4'), 'key3' : ('value5, value6')}

I tried d[key][0] in the hope it would return "value1" but instead it return "v"

Any suggestions?

+4  A: 

Try something like this:

d = {'key' : 'value1, value2'}

list = d['key'].split(', ')

list[0] will be "value1" and list[1] will be "value2".

Andrew Hare
+15  A: 

A better solution is to store your value as a two-tuple:

d = {'key' : ('value1', 'value2')}

That way you don't have to split every time you want to access the values.

zenazn
Ok I agree I think this is a better idea also, but I am still in the dark as to the syntax required to extract the values separately?
Joe
@Joe: `d['key'][0]` and `d['key'][1]`
Adam Bernier
@Adam Bernier: I tried that but it gives me the first letter of each string...? help!
Joe
A better way would be to use tuple decomposition: `v1, v2 = d['key']`
Pavel Minaev
@Joe: please update the question with the code you are trying. My guess is that you have a minor syntax error, but we cannot help if we do not see what you are doing.
Adam Bernier
@Adam Bernier:Updated.
Joe
@Joe: based on your edit, your problem is that you are still using one string. Pay careful attention to the quotes: `d= {'key' : ('value1', 'value2'), 'key2' : ('value3', 'value4'), 'key3' : ('value5', 'value6')}`
Adam Bernier
@Adam Bernier: Haha many thanks, thats what happens when you have been working over 12 hours. Thanks again for your time!
Joe
@Joe: no worries; happens to us all.
Adam Bernier
+1  A: 

I would suggest storing lists in your dictionary. It'd make it much easier to reference. For instance,

from collections import defaultdict

my_dict = defaultdict(list)
my_dict["key"].append("value 1")
my_dict["key"].append("value 2")

print my_dict["key"][1]
Evan Fosmark
A: 

To obtain the two values and assign them to value1 and value2:

for v in d.itervalues():
    value1, value2 = v.split(', ')

As said by zenazn, I wouldn't consider this to be a sensible data structure, using a tuple or a class to store the multiple values would be better.

gridzbi
A: 

The way you're storing your values, you'll need something like:

value1, value2 = d['key'].split(', ')
print value1, value2

or to iterate over all values:

for key in d:
    v1, v2 = d[k].split(', ')
    print v1, v2

But, if you can, you should probably follow zenazn's suggestion of storing your values as tuples, and avoid the need to split every time.

ars