user3240735 user3240735 - 27 days ago 5
Python Question

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

Answer

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

Comments