简体   繁体   English

访问列表中字典中的项目

[英]Accessing items in a dictionary within a list

I'm trying to access the only the keys of a dictionary within a list that contains integers and strings.我正在尝试访问包含整数和字符串的列表中字典的唯一键。 Here is an example of the what that list looks like:这是该列表的示例:

list =[
101, a, e, {'a': 1, 'b': 2}, 
202, b, f, {'c': 2, 'd': 3}, 
303, c, g, {'e': 3, 'b': 4}, 
404, d, h, {'g': 2, 'h': 4}, 
505, d, i, {'i': 3, 'j': 4}
]

I'm able to access each element of the list but not sure how to access the dictionaries of each item.我能够访问列表的每个元素,但不确定如何访问每个项目的字典。

First of all, don't use builtin keywords of the language like list for variables, it can cause very nasty bugs in your code.首先,不要使用语言的内置关键字,如变量list ,它会导致代码中非常讨厌的错误。 To get the keys of the dictionaries, loop through the list and check if the current value is a dictionary, for example:要获取字典的键,请遍历列表并检查当前值是否为字典,例如:

l = [
101, 'a', 'e', {'a': 1, 'b': 2}, 
202, 'b', 'f', {'c': 2, 'd': 3}, 
303, 'c', 'g', {'e': 3, 'b': 4}, 
404, 'd', 'h', {'g': 2, 'h': 4}, 
505, 'd', 'i', {'i': 3, 'j': 4}
]

keys = [ 
  list(d.keys()) for d in l if isinstance(d,dict)
]

print(keys)
>>> [['a', 'b'], ['c', 'd'], ['e', 'b'], ['g', 'h'], ['i', 'j']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM