简体   繁体   中英

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. 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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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