简体   繁体   中英

How do I select from a dictionary whose values are a list of lists in python2.7?

I have a dictionary with key value pairs, as they are. The values are all lists or lists of lists.

For a dictionary that looks like this:

    d={}
    d['FM_001323'] = [[45,11232],[300,400],[65,700]]
    d['FM_094326'] = [11500,12500]

If I want to see the first entry for each list in the value by each key, I can't just do the below like I could if every entry was a list of lists:

    for j in d:
           for i in range(0,len(d[j]):
                  print d[j][i][0]

Because the second key in my dictionary only has a single list for a value, not a list of lists, and the [0] index doesn't have any reference. Does that make sense?

I want to isolate the first entry in each list-value for each key. It's easy with either list-values or lists of list-values, but mixing them together complicates it.

I am also open to easier ways to reach the same goal. For context: I am trying to compare the numbers in the values with variables from other parts of this code by that FM_ figure. Any way of isolating these would suffice for me.

Expected output would be

    45
    300
    65
    11500

One way of doing is "Asked Forgiveness Not Permission"

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]

for j in d:
    for i in range(0,len(d[j])):
        try:
            print(d[j][i][0])
        except TypeError:
            print(d[j][0])
            break

prints:

45
300
65
11500

Basically just do it in try blocks and catch the exception that will throw if it didn't work out and try it again with something else.

Edited so to OP's desired output. Just break out of the loop after the first print because your second for loop is there to loop through the sub lists right? You don't have a sub list so just break out of it

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]
for k in d:
    for v in d[k]:
        if isinstance(v, list): 
            print v[0]    
        else:
            print v

Output: 45 300 65 11500 12500

Or cleaner and shorter:

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]

for j in d.itervalues():
    for i in j:
        if isinstance(i,list):
            print(i[0])
        else:
            print(i)

Only a single additional line is required in your code. You should have a check on the element type. Something like this:

for j in d:
    for i in range(0,len(d[j])):
        #See the line below.
        if type(d[j][i]) == type([]):
           print(d[j][i][0])
        else
            print(d[j][i])

Note: in case you want to print only the first element when the d[j] only have numbers and no lists. you may have to run an additional loop to find out whether d[j] has any list in it or not. See code below:

for j in d:
    #Check if all elements in d[j] are int.
    for i in d[j]:
        if type(i) ==type([]):
            break
    else:
        print(d[j][0])
        continue

    for i in range(0,len(d[j])):
        #See the line below.
        if type(d[j][i]) == type([]):
           print(d[j][i][0])
        else:
            print(d[j][i])

So for d[j] = [11500,[1,2],1300] , 11500 1 and 1300 would be printed.

Another way would be to convert to str first and march on r'\\[{0-9}+' , which would give all leading elements:

from __future__ import print_function
import re

d={}
d['FM_001323'] = [[45,11232],[300,400],[65,700]]
d['FM_094326'] = [11500,12500]

for v in d.values():
    print('\n'.join(s[1:] for s in re.findall(r'\[[0-9]+', str(v))))

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