0

I have a dict that looks like the following:

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

I'm trying to iterate through all its values like the following:

for i in myDict.iterkeys():
    for j in range(0,len(myDict[i])):
        print myDict[i][j]

I saw couple posts on stackoverflow here and here. but I'm wondering if there is a faster way of doing that without having to use two for loops?

Community
  • 1
  • 1
tkyass
  • 2,968
  • 8
  • 38
  • 57
  • Not really. You want to iterate over the values (each list) then each member of the given list, so you have to have two loops in the most general sense. There's probably some optimizations depending on what you're trying to do. (For instance, `for lst in myDict.values(): for value in lst: print value`) – Two-Bit Alchemist Jun 15 '16 at 19:25
  • 2
    just because are having 2 nested loops that does not automatically mean the code is slow – RomCoo Jun 15 '16 at 19:25

3 Answers3

2

You can just say

for sub_list in myDict.values():
    for item in sub_list:
        print(item)

But that doesn't really answer your loop in a loop question. There isn't going to be a solution for nested iteration given a dictionary that contains lists.

AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103
2

Here is a solution with one for loop.

for i in reduce(lambda x, y: x+y, myDict.values()):
    print i

myDict.values it's a list of list.

In [33]: myDict.values()
Out[33]: [['1', '2', '3'], ['1', '2', '3', '4'], ['1', '2']]

With using reduce i made it as like a single list.

In [34]: reduce(lambda x, y: x+y, myDict.values())
Out[34]: ['1', '2', '3', '1', '2', '3', '4', '1', '2']

And iterate though it

Edit

Regarding time of execution using timeit

In [69]: def test1():
    for sublist in myDict.values():
            for value in sublist:
                    print(value)
   ....:             
In [70]: def test2():
    for i in reduce(lambda x, y: x+y, myDict.values()):
            print i
   ....:         
In [71]: %timeit test1
10000000 loops, best of 3: 27 ns per loop
In [72]: %timeit test2
10000000 loops, best of 3: 25.6 ns per loop

It's perform better.

Perform as per the timeit module

In [81]: timeit.timeit(test2, number=10000)
Out[81]: 0.016376018524169922
In [82]: timeit.timeit(test1, number=10000)
Out[82]: 0.023879051208496094
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
  • @tkyass It might work but is it readable? Also is it efficient? Might be worth doing some tests with [**`timeit`**](https://docs.python.org/2/library/timeit.html). – Peter Wood Jun 16 '16 at 15:42
1

You can just get the values from the dictionary, and the values from the sublist, no need to key or index:

for sublist in myDict.values():
    for value in sublist:
        print(value)
Peter Wood
  • 23,859
  • 5
  • 60
  • 99