Reputation: 115
I have a json and I need to create a list of list like:
lista = [['334507', 'XXX', '334507', 36.07, 3985499.0],
['271018','YYY', '271007', 23.11, 1335150.0]]
all_sites = {
u'displayValue': {
u'siteId': {u'334507': u'XXX', u'271018': u'YYY'}
},
u'rows': [[u'334507', 36.07, 3985499.0],
[u'271018', 23.11, 1335150.0]],
u'alert': None,
u'columns': [u'siteId', u'revenue', u'paidImpressions'],
u'currency': u'USD'
}
I tried with something like this:
sites = all_sites['displayValue']['siteId'].items()
sites_data = all_sites['rows']
data = []
for item in sites:
data.append(list(item))
for item in sites_data:
data.append(item)
But how can I merge the list with the first item of the list??
Upvotes: 2
Views: 72
Reputation: 2117
Below example may help you.
json_ = {u'displayValue': {u'siteId': {u'334507': u'XXX', u'271018': u'YYY'}},
u'rows': [[u'334507', 36.07, 3985499.0], [u'271007', 23.11, 1335150.0]],
u'alert': None,
u'columns': [u'siteId', u'revenue', u'paidImpressions'],
u'currency': u'USD'}
result = []
count = len(json_["displayValue"]["siteId"])
for element in range(count):
item = list(json_["displayValue"]["siteId"].items()[element])+json_["rows"][element]
result.append(item)
print result
Output:
[[u'334507', u'XXX', u'334507', 36.07, 3985499.0], [u'271018', u'YYY', u'271007', 23.11, 1335150.0]]
Upvotes: 0
Reputation: 38962
You can enumerate the siteId
field items.
Then zip this with the list in the rows
field.
Iterate over the zip and extend each item
(note that item should be converted to a list before extending it) with its matching row
.
siteid_items = json_['displayValue']['siteId'].items()
rows = json_["rows"]
result = list(
list(item) + row
for item, row in zip(siteid_items, rows)
)
print(result)
'''
stdout:
[['334507', 'XXX', '334507', 36.07, 3985499.0],
['271018', 'YYY', '271018', 23.11, 1335150.0]]
'''
Upvotes: 1
Reputation: 1187
Just giving what you asked for :)
[[k,v]+all_sites['rows'][i] for i, (k,v) in enumerate(all_sites['displayValue']['siteId'].items())]
First, iterate over the siteId:
>>> [t for t in all_sites['displayValue']['siteId'].items()]
[('334507', 'XXX'), ('271018', 'YYY')]
Now, you know that it will give you a tuple in t, which you might replace as:
>>> [[k,v] for k,v in all_sites['displayValue']['siteId'].items()]
[['334507', 'XXX'], ['271018', 'YYY']]
Now, the other items are in the "rows" key, but you need to know the row's index. One way of knowing the index of each (k,v) tuple is:
>>> [[k,v]+[i] for i, (k,v) in enumerate(all_sites['displayValue']['siteId'].items())]
[['334507', 'XXX', 0], ['271018', 'YYY', 1]]
See that it merges the list [k,v] with the list [i]. Now, all you have to do is take the row you are interested for each index:
>>> [[k,v]+all_sites['rows'][i] for i, (k,v) in enumerate(all_sites['displayValue']['siteId'].items())]
[['334507', 'XXX', '334507', 36.07, 3985499.0],
['271018', 'YYY', '271018', 23.11, 1335150.0]]
I hope that helps.
Upvotes: 2