Reputation: 1
for example I have a dict var defined as below:
var{m:(a, b)}
And now I want to reference the value of 'a' in a for loop
suppose var is filled with some instances as below
var = {0: {'1a': (502, 2)}, 1: {'2b': (103, 3)}}
Upvotes: 0
Views: 224
Reputation: 17158
Right, so you want v[0]['1a'][0]
EDIT: In response to your comment, you probably want:
for key, value in v[k].items():
print value[0]
Upvotes: 1
Reputation: 86366
Is this what you are looking for?
var = {'m':('a', 'b'), 'n': ('c','d')}
a_coords = [(k,v.index('a')) for k,v in var.iteritems() if 'a' in v ]
Result:
>>> a_coords
[('m', 0)]
'm'
is the key that is associated with the value of a tuple that holds a, and 0
is the index where a is located.
Upvotes: 0
Reputation: 6434
Let's see if this generic example can make it clear by naming the items we get descriptively.
var = {0: {'1a': (502, 2)}, 1: {'2b': (103, 3)}}
You want to iterate on all dicts that var contains and iterate on what they contain.
for number, innerdict in var.items(): # first time around number is e.g. 0 and innerdict is e.g. {'1a': (502, 2)}
print number
for numberletter, tup in innerdict.items(): # first time around numberletter is e.g. 1a and tup is e.g. (502, 2)
print numberletter, tup
for tuplenumber in tup: # first time around tuplenumber is e.g. 502
print tuplenumber
Upvotes: 0
Reputation: 9161
You may want, rather:
for k, (v1, v2) in var.iteritems():
print v1
Or if not all of your dict values are going to have two items (or if your version of Python doesn't do multilevel tuple unpacking):
for k, v in var.iteritems():
print v[0]
Upvotes: 1
Reputation: 4926
May be this is what you are wanting:
var = {0: {'1a': (502, 2)}, 1: {'2b': (103, 3)}}
for m, elements in var.items():
for a, b in elements.values():
print a
Upvotes: 1