lundi 13 juin 2016

Extracting values from nested list/tuple/dictionary

Here's a list that was originally a dictionary that was converted due to sorting;

list1 = [ 
            ('key1', {'count': 10, 'value1': Counter({'set1': 5, 'set2': 4, 'set3': 1})}), 
            ('key2', {'count': 8, 'value2': Counter({'set1': 6, 'set2': 2})}),
            ('key3', {'count': 7, 'value3': Counter({'set1': 5, 'set2': 2, 'set3': 1})}) 
        ]

What I'm trying get is the first two 'key' objects (along with its count) , and the first 'value' object (along with its count) of each key. For example I'm trying to get a print output of;

key1 10
set1 5

key2 8
set1 6

Edit: This is what I've already tried (and played around with);

for key, value in sorted_x:
    print key, value - only gives key/value as a whole
for key, value in sorted_x:
    print key, value[0] - gives keyerror. I've tried a few variations including nested loops.
for key, value in sorted_x.iteritems():
    print key, value

I've tried doing nested loops, along with trying to get parts of the list [1]. But I haven't been able to pin point the data I want and keep getting 'unpack' error messages.

Aucun commentaire:

Enregistrer un commentaire