我是Python的新手,我想知道如何迭代字典列表中的部分键。
假设我有类似的东西:
OrderedDict([('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')])
OrderedDict([('name', 'Bob'), ('AAA', '31'), ('BBB', '21'), ('CCC', '41')])
etc.
我需要检索并遍历AAA,BBB,CCC(键,而不是值),但是:
如果您能提供帮助,我将非常高兴
非常感谢!
答案 0 :(得分:2)
只需遍历第一个列表,然后检查它是否为name
,就可以跳过它。
for key in list_of_dicts[0]:
if key != 'name':
print(key)
答案 1 :(得分:1)
您可以使用以下方法从第一行中提取密钥:
keys = (key for key in list_of_dicts[0] if key != 'name')
现在,您可以使用类似的方法遍历按键:
for var in keys:
print(var)
答案 2 :(得分:1)
我不确定这是否是最好的方法,但是我会这样做:
Dict = OrderedDict([('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')])
keys = [] # keys is an empty list
for i in Dict: # Iterate over all keys in the dictionary
if i != 'name': # Exclude 'name' from the list
keys.append(i) # Append each 'i' to the list
这将为您提供Dict中每个键的列表,键,但不包括“名称”。
现在,您可以像这样遍历键:
for i in keys:
print(i) # Do something with each key
如果您还想遍历值:
for i in keys:
print(Dict[i]) # Do something with each value
答案 3 :(得分:0)
您将使用for
循环。这是一个示例(我叫i
,因为我不知道您称该函数的参数为什么):
i = [('name', 'Anna'), ('AAA', '15'), ('BBB', '49'), ('CCC', '38')]
for a in range(len(i)):
print(i[a][1])
上面的方法获得了a
的索引,而在元组(具有2个元素,因此0
或1
的元组中)获得了第二个索引。
注意:
您可能想创建一个嵌套的for循环,以在元组中获得理想值。
答案 4 :(得分:0)
这是您可以做的:
lst = [{...}, {...}, {...}, {...}, ...]
f = ['name']
for d in lst: # For every dict in the list
for k in d: # For every key in the dict
if k not in f: # If the key is not in the list f
# Do something
f.append(k) # Add that key to f so the program won't iterate through it again
更新
(我刚刚发现每个字典都具有相同的键,因此无需进行所有检查):
lst = [{...}, {...}, {...}, {...}, ...]
for d in lst: # For every dict in the list
for k in d: # For every key in the dict
if k != 'name': # If the key is not 'name'
# Do something