Question

I'm new to python know there is a better way to do this extremely simple task but I dont seem to be asking the right questions and I am hoping someone here can give me some advice on how to neaten up my code - I feel like I am writing way to much code to do what I am doing.

I'm tagging my recorded tv shows with tvdb_api. The api returns the banners in an interesting structure (dict nesting tuples nesting dicts) the basic structure is:

{"684x400":
    {"949520":
        {"_bannerpath": "http://tvdb.com/banners/somepath",
         "rating" : 9.000
         #etc...
        },
     "456520":
        {"_bannerpath": "http://tvdb.com/banners/somepath",
            "rating" : 9.000
            #and so on...
        }
    }
}

I loop over the items in the data structure, compare the rating values and get the _bannerpath of the highest rated banner. I do this by getting all of the rating and _bannerpath values from the structure and copying them into as nested lists into a list and then seperating out the rating values into another list and using max to get the highest value and returning the corresponding bannerpath!

There MUST be a better way than this!

posterList = []

for tup in bannerStructure:
            for key in tup[1]:
                    if key == "rating":
                            posterList.append([tup[1]['rating'],tup[1]['_bannerpath']])
        ratingList = []

        for rating in posterList:
            ratingList.append(rating[0])

        maxRating = max(ratingList)

        for lst in posterList:
            if lst[0] == maxRating:
                return lst[1]

thankyou for your help!

Was it helpful?

Solution

Assuming the actual structure is like this:

{"684x400":
    {"949520":
        {"_bannerpath": "http://tvdb.com/banners/somepath",
         "rating" : 9.000
         #etc...
        },
     "456520":
        {"_bannerpath": "http://tvdb.com/banners/somepath",
         "rating" : 9.000
         #and so on...
        }
    }
}

Then to find a banner with the highest rating for each resolution:

from operator import itemgetter

for resolution, banners in tvdb_api_result.items():
    bannerpath = max(banners.values(), key=itemgetter('rating'))['_bannerpath']
    print("%s %s" % (resolution, bannerpath))

OTHER TIPS

You can use comprehension and max function to get this

max([(k["_bannerpath"], k["rating"]) for v in data.values() for k in v.values()], key=lambda x:x[1])
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top