简体   繁体   中英

Iterating over a variable sized lists in Python dict

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?

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.

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

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)

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