[英]Python dict with three values in the for loop
Using python I have some code that looks like this: 使用python我有一些看起来像这样的代码:
for (key, value) in files:
...
A working list for the above could be: 上面的工作清单可能是:
files = [(
'key1', 'value1'
), ...]
I now found this code: 我现在发现此代码:
for (key, filename, value) in files:
...
How would the dict look for me to get key
, filename
and value
? 字典将如何寻找我获取
key
, filename
和value
?
Do you want a dict or a list like you have supplied? 您想要像您提供的字典或列表吗? If you want to keep it as a list you could just extend the tuple to have three items instead of two like so.
如果要将其保留为列表,则可以将元组扩展为具有三个项目,而不是像这样的两个。 I assume from your wording you want to know what the files variable would look like in order to fit with that loop.
我假设从您的措辞中您想知道files变量是什么样的,以便适合该循环。 This should suffice:
这样就足够了:
files = [
('key1', 'file1', 'value1'),
('key2', 'file2', 'value2'),
('key3', 'file3', 'value3')
]
for (key, file, value) in files:
print key, file, value
>>key1 file1 value1
>>key2 file2 value2
>>key3 file3 value3
If you want it to be a dict you would probably want to format it like this: 如果您希望将其作为字典,则可能需要这样格式化:
files = {
'key1': ('file1', 'value1'),
'key2': ('file2', 'value2'),
'key3': ('file3', 'value3')
}
for key, value in files.iteritems():
print key, value[0], value[1]
>>key3 file3 value3
>>key2 file2 value2
>>key1 file1 value1
However be aware that dict's won't keep the order of the items if that is important to you. 但是请注意,如果这对您很重要,那么dict不会保留项目的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.