[英]Python: How to reference element of a tuple that is in a dictionary
for example I have a dict var defined as below: 例如我有一个dict var定义如下:
var{m:(a, b)}
And now I want to reference the value of 'a' in a for loop 现在我想在for循环中引用'a'的值
suppose var is filled with some instances as below 假设var充满了一些实例,如下所示
var = {0: {'1a': (502, 2)}, 1: {'2b': (103, 3)}}
Right, so you want v[0]['1a'][0]
是的,所以你想要
v[0]['1a'][0]
EDIT: In response to your comment, you probably want: 编辑:为了回应您的评论,您可能想要:
for key, value in v[k].items():
print value[0]
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
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): 或者,如果不是所有的dict值都包含两个项(或者您的Python版本没有对多级元组进行拆包):
for k, v in var.iteritems():
print v[0]
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. 您想遍历var包含的所有字典,并遍历它们包含的所有字典。
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
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. 'm'
是与保存a的元组的值关联的键, 0
是a所在的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.