1

consider i'm getting out from a row where row[0],row[1],row[2] consists of below output and it comes in same order as below:

'Testcase2', 37L, 'hydra.c
'Testcase2', 100L,'vendor.c
'Testcase7', 34L, 'template.c
'Testcase3', 88L, 'hydra.c
'Testcase3', 80L, 'vendor.c
'Testcase6', 81L, 'template.c
'Testcase1', 1L, 'hydra.c
'Testcase4', 89L, 'vendor.c
'Testcase8', 41L, 'template.c
'Testcase5', 83L, 'vendor.c
'Testcase4', 98L, 'template.c

i need a unique test case names to be printed along with maximum row[1] value so i thought of creating dictionary with multiple values.

{'Testcase1': {'hydra.c': 1},
 'Testcase2':{'hydra.c':37,'vendor.c':100 },
 'Testcase3':{'hydra.c':1,'vendor.c':80}
 'Testcase4':{'vendor.c':89,'template.c':98},
 'Testcase5':{'vendor.c':83}
 'Testcase6':{'template.c':34}....} 

for creating dictionary with multiple values as above please do help me so that later i will do sorting of nested dict so that later i ll print testcase name with highest row[1] value:

from pprint import pprint as pp
d={}
for x,y,z in row:
    d.setdefault(x,{z:[]})
    d[x][z].append(y)

pp(d)

i tried above code but its updating only with new file name its not appending as above requirement.

3
  • stackoverflow.com/help/how-to-ask Commented Nov 21, 2017 at 4:43
  • And what have you tried in order to achieve this? Commented Nov 21, 2017 at 5:01
  • i have added my code Commented Nov 21, 2017 at 5:08

1 Answer 1

1

Append is a list operation. Based on your example data, it appears you anticipate distinct z's for a given x:

    for x, y, z in row:
        if x not in d:
            d[x] = {}
        d[x][z] = y

But that if is a common pattern addressed in collections:

from collections import defaultdict

    d = defaultdict(dict)
    for x, y, z in row:
        d[x][z] = y
Sign up to request clarification or add additional context in comments.

3 Comments

how to sort 'd' based on value 'y'
A dict makes no promises about being sorted. You'll want some sortable data structure, such as a list. Initialize with lst = [], and after assigning d[x][z] = y, also do lst.append((y, x, z)) (or the tuple y, z, x if that is what your question was asking). Then sorted(lst) gives the desired result. To make it look nice, use pprint.pprint(sorted(lst)).
A revision to this if x not in d: d[x] = {} d[x][z] = y is needlessly slow this is faster: going with try/except KeyError catch is way faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.