Home > front end >  Iterate over lists inside a dictionary
Iterate over lists inside a dictionary

Time:05-06

Is there any way to iterate over lists inside a dictionary. A key inside dictionary contains a list which needs to be iterated over separately from the other lists. When I try to iterate over the dictionary, it iterates over the 0th element of each key.value instead of iterating over one list.

as an example, the dictionary below should be iterated. First the iteration should be able to access the list inside 'a' separately and the list inside 'b'.

d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}

CodePudding user response:

To iterate in the lists inside the dictionary you can try something like this,

d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}

for key in d:
  for item in d[key]:
    print(item) #Change this line to whatever you want to do

To iterate only on a do,

for item in d["a"]:
    print(item)

CodePudding user response:

d = {'a' : [1,2,3,4], 'b': [2,2,2,2]}

for k,v in d.items():
  for item in d[k]:
    print(item)
  • Related