'Iterate over lists inside a dictionary

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]}



Solution 1:[1]

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)

Solution 2:[2]

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

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

Solution 3:[3]

You can use a list comprehension like so:

[print(num) for lst in d.values() for num in lst]

The list is not saved at the end.

Solution 4:[4]

Using from_iterable :

import itertools

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

for key, value in (
        itertools.chain.from_iterable((itertools.product((k,), v) for k, v in d.items()))):
        
        if(key=='a'):
            print(value)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ender Dangered
Solution 3 Jake Korman
Solution 4 AlI