gdogg371
gdogg371

Reputation: 4142

Using list elements to create .format() mapping for .json() object?

I have the following object being returned using response.json within the Requests module:

{u'statColumns': [u'apps', u'subOn', u'minsPlayed', u'tackleWonTotal', u'challengeLost', 
u'tackleTotalAttempted'], u'paging': {u'firstRecordIndex': 1, u'resultsPerPage': 1,     u'lastRecordIndex':
1, u'totalPages': 431, u'currentPage': 1, u'totalResults': 431}, u'playerTableStats': 
[{u'positionText': u'Defender', u'rating': 8.37, u'weight': 77, u'playerId': 22079, u'height': 188, 
u'teamId': 32, u'playedPositions': u'-DC-', u'challengeLost': 0.0, u'isManOfTheMatch': False, u'isOpta':
True, u'subOn': 0, u'tackleWonTotal': 2.0, u'tournamentShortName': u'EPL', u'apps': 1, u'teamName':
u'Manchester United', u'tournamentRegionId': 252, u'regionCode': u'gb-nir', u'tournamentRegionCode':
u'gb-eng', u'playedPositionsShort': u'D(C)', u'seasonId': 4311, u'ranking': 1, u'minsPlayed': 90, 
u'tournamentName': u'Premier League', u'isActive': True, u'name': u'Jonny Evans', u'firstName': 
u'Jonny', u'lastName': u'Evans', u'age': 26, u'seasonName': u'2014/2015', u'tournamentId': 2,
u'tackleTotalAttempted': 2.0}]}

This object has two elements, playerTableStats and statColumns. These can accessed with the following code:

playerTableStats = response[u'playerTableStats']
statColumns = response[u'statColumns']

If I convert the contents of statColumns into a string object, I can use it as part of a .format() statement to map playerTableStats. I could do this like so:

var1 = ['one','two','three','four']
var1 = 'u"{',var1[0],'}','{',var1[1],'}','{',var1[2],'}','{',var1[3],'}"'
var1 = ''.join(var1)

var2 = (var1.format(**responser))

print var2

However that doesn't seem very Pythonic and doesn't take into account the fact that both statColumns and playerTableStats will vary in their number of elements when I am returning different .json objects from the same site.

Is there a cleaner way to get all elements of statColumns into the format:

u"{one}{two}{three}{four}"

Thanks

Upvotes: 0

Views: 69

Answers (1)

falsetru
falsetru

Reputation: 369364

Using str.join with generator expression:

var2 = ''.join('{' + x + '}' for x in var1)

Upvotes: 1

Related Questions