Reputation: 7051
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?
Upvotes: 2
Views: 622
Reputation: 123468
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.
Upvotes: 0
Reputation: 1199
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.
Upvotes: 2
Reputation: 101651
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]
Upvotes: 2
Reputation: 14345
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.
Upvotes: 17
Reputation: 351456
Try something like this:
d = {'key' : 'value1, value2'}
list = d['key'].split(', ')
list[0]
will be "value1" and list[1]
will be "value2".
Upvotes: 4