I am trying to create a breadth first search with a data set. I need to iterate through the data set but I'm not sure how to iterate through my list of dictionaries that contain a list.
I know to access say node 2
second value, I would do a[1]['node2][1]
. However, I'm not sure how to iterate through each name.
This isn't actual code but I would want something similar to this:
for key_of_dict in a:
print key_of_dict
for j in a[key_of_dict]
print ": " + j
#This pseudo code should print the key and the data in the list of the respective dict
ex:
a =
[
{'node1':[1,2,3]},
{'node2':[4,5,6]},
{'node3':[7,8,9]},
{'node4':['a','b','c']}
]
Simply iterate through dict.values()
:
for d in a:
for v in d.values():
print(v)
Demo:
>>> for d in a:
for v in d.values():
print(*v)
1 2 3
4 5 6
7 8 9
a b c
Or if you print just v
:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
['a', 'b', 'c']
To get the keys as well, iterate through d.items()
, which will return key-value pairs of the dict.
Hope this helps!
a = [{'node1':[1,2,3]},
{'node2':[4,5,6]},
{'node3':[7,8,9]},
{'node4':['a','b','c']}]
python 2.7:
for dict in a:
for key,list in dict.iteritems():
print '{} : {}'.format(key,list)
python 3:
for dict in a:
for key,list in dict.items():
print('{} : {}'.format(key,list))
output:
node1 : [1, 2, 3]
node2 : [4, 5, 6]
node3 : [7, 8, 9]
node4 : ['a', 'b', 'c']
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.