Objective: Append items from value['itemArray'] to Products['Items'] - see function fba_orders
Problem: The Current code only appends the last item of value['itemArray'] to Products['Items']
Current Output:
{'Items': [{'SellerFulfillmentOrderItemId': 266804219, 'SellerSKU': 'IX-GZ31-31K6', 'Quantity': 1}, {'SellerFulfillmentOrderItemId': 266804219, 'SellerSKU': 'IX-GZ31-31K6', 'Quantity': 1}]}
Correct Output would be:
{'Items': [{'SellerFulfillmentOrderItemId': 266804218, 'SellerSKU': 'KM-090914-840-BEARLAPTOP', 'Quantity': 1}, {'SellerFulfillmentOrderItemId': 266804219, 'SellerSKU': 'IX-GZ31-31K6', 'Quantity': 1}]}
Code:
import sys
VALUE = {'amountPaid': '43.38',
'amountSaved': 0.0,
'buyerCheckoutMessage': '',
'buyerUserID': 13182254,
'buyerUserName': 'W5Tiny',
'checkoutStatus': {'status': 'Complete'},
'createdTime': '2015-06-30T22:41:01Z',
'creatingUserRole': 'Buyer',
'itemArray': [{'item': {'itemID': 266804218,
'price': '21.1',
'quantity': 1,
'sellerInventoryID': 'KM-090914-840-BEARLAPTOP',
'sk': 'KM-090914-840-BEARLAPTOP',
'title': u"VTech Bear's Baby Laptop, Blue [Toy]"}},
{'item': {'itemID': 266804219,
'price': '22.28',
'quantity': 1,
'sellerInventoryID': 'IX-GZ31-31K6',
'sk': 'IX-GZ31-31K6',
'title': 'Toy State Caterpillar Push Powered Rev It Up Dump Truck [Toy]'}}],
'orderID': 34013525,
'orderStatus': 'Completed',
'paidTime': '2015-06-30T22:50:38Z',
'shippingAddress': {'addressID': 15798541,
'cityName': 'Nashville',
'country': 'US',
'countryName': None,
'name': 'UNKNOWN',
'postalCode': '37221',
'stateOrProvince': 'TN',
'street1': '123 BOOGIE DRIVE',
'street2': None},
'shippingDetails': {'amount': '0.0',
'insuranceFee': 0,
'servicesArray': [],
'shippingService': 'Standard shipping'},
'subtotal': 43.38,
'taxAmount': 0.0,
'total': '43.38',
'transactionArray': {'transaction': {'buyer': {'email': 'fakewilson259612#hotmail.com'},
'finalValueFee': '0.0',
'providerID': '11V84334FD304010L',
'providerName': 'Paypal'}}}
def fba_order():
address = {}
products = {'Items': []}
item = {}
Items = []
address['City'] = VALUE['shippingAddress']['cityName']
address['CountryCode'] = VALUE['shippingAddress']['country']
address['Line1'] = VALUE['shippingAddress']['street1']
address['Line2'] = VALUE['shippingAddress']['street2']
address['Name'] = VALUE['shippingAddress']['name']
address['PostalCode'] = VALUE['shippingAddress']['postalCode']
address['StateOrProvinceCode'] = VALUE['shippingAddress']['stateOrProvince']
for items in VALUE['itemArray']:
item['Quantity'] = items['item']['quantity']
item['SellerFulfillmentOrderItemId'] = items['item']['itemID']
item['SellerSKU'] = items['item']['sk']
products['Items'].append(item)
continue
print address, '\n', products
if __name__ == '__main__':
sys.exit(fba_order())
You are reusing the dictionary referenced by item over and over again; appending this one dictionary won't create a new copy. Rather, you are adding multiple references to that one dictionary. As you continue to alter the dictionary all those references will show those changes.
Better produce an entirely new dictionary for each loop iteration:
for items in VALUE['itemArray']:
item = {
'Quantity': items['item']['quantity'],
'SellerFulfillmentOrderItemId': items['item']['itemID']
'SellerSKU': items['item']['sk'],
}
products['Items'].append(item)
The issue is that you are creating item outside the for loop and then just changing the values inside the for loop and appending it to the list.
dictionaries are reference, and hence even after appending to products['Items'] list if you change the item dictionary it will make changes to the item that was appended to the list.
You want to initialize item to a new dictionary inside the for loop.
Example -
def fba_order():
address = {}
products = {'Items': []}
Items = []
address['City'] = VALUE['shippingAddress']['cityName']
address['CountryCode'] = VALUE['shippingAddress']['country']
address['Line1'] = VALUE['shippingAddress']['street1']
address['Line2'] = VALUE['shippingAddress']['street2']
address['Name'] = VALUE['shippingAddress']['name']
address['PostalCode'] = VALUE['shippingAddress']['postalCode']
address['StateOrProvinceCode'] = VALUE['shippingAddress']['stateOrProvince']
for items in VALUE['itemArray']:
item = {}
item['Quantity'] = items['item']['quantity']
item['SellerFulfillmentOrderItemId'] = items['item']['itemID']
item['SellerSKU'] = items['item']['sk']
products['Items'].append(item)
continue
print address, '\n', products
Related
I have a relatively simple nested dictionary as below:
emp_details = {
'Employee': {
'jim': {'ID':'001', 'Sales':'75000', 'Title': 'Lead'},
'eva': {'ID':'002', 'Sales': '50000', 'Title': 'Associate'},
'tony': {'ID':'003', 'Sales': '150000', 'Title': 'Manager'}
}
}
I can get the sales info of 'eva' easily by:
print(emp_details['Employee']['eva']['Sales'])
but I'm having difficulty writing a statement to extract information on all employees whose sales are over 50000.
You can't use one statement because the list initializer expression can't have an if without an else.
Use a for loop:
result = {} # dict expression
result_list = [] # list expression using (key, value)
for key, value in list(emp_details['Employee'].items())): # iterate from all items in dictionary
if int(value['Sales']) > 50000: # your judgement
result[key] = value # add to dict
result_list.append((key, value)) # add to list
print(result)
print(result_list)
# should say:
'''
{'jim': {'ID':'001', 'Sales':'75000', 'Title': 'Lead'}, 'tony': {'ID':'003', 'Sales': '150000', 'Title': 'Manager'}}
[('jim', {'ID':'001', 'Sales':'75000', 'Title': 'Lead'}), ('tony', {'ID':'003', 'Sales': '150000', 'Title': 'Manager'})]
'''
Your Sales is of String type.
Therefore, we can do something like this to get the information of employees whose sales are over 50000 : -
Method1 :
If you just want to get the information : -
emp_details={'Employee':{'jim':{'ID':'001', 'Sales':'75000', 'Title': 'Lead'}, \
'eva':{'ID':'002', 'Sales': '50000', 'Title': 'Associate'}, \
'tony':{'ID':'003', 'Sales': '150000', 'Title': 'Manager'}
}}
for emp in emp_details['Employee']:
if int(emp_details['Employee'][emp]['Sales']) > 50000:
print(emp_details['Employee'][emp])
It print outs to -:
{'ID': '001', 'Sales': '75000', 'Title': 'Lead'}
{'ID': '003', 'Sales': '150000', 'Title': 'Manager'}
Method2 : You can use Dict and List comprehension to get complete information : -
emp_details={'Employee':{'jim':{'ID':'001', 'Sales':'75000', 'Title': 'Lead'}, \
'eva':{'ID':'002', 'Sales': '50000', 'Title': 'Associate'}, \
'tony':{'ID':'003', 'Sales': '150000', 'Title': 'Manager'}
}}
emp_details_dictComp = {k:v for k,v in list(emp_details['Employee'].items()) if int(v['Sales']) > 50000}
print(emp_details_dictComp)
emp_details_listComp = [(k,v) for k,v in list(emp_details['Employee'].items()) if int(v['Sales']) > 50000]
print(emp_details_listComp)
Result : -
{'jim': {'ID': '001', 'Sales': '75000', 'Title': 'Lead'}, 'tony': {'ID': '003', 'Sales': '150000', 'Title': 'Manager'}}
[('jim', {'ID': '001', 'Sales': '75000', 'Title': 'Lead'}), ('tony', {'ID': '003', 'Sales': '150000', 'Title': 'Manager'})]
Help me please.
I have query set from Model.objects.value('name', 'language__name') and it give me the list of dictionary:
list = [{'id': 1, 'name': 'Adel', 'language': 'С#'},
{'id': 1, 'name': 'Adel', 'language': 'Python'},
{'id': 5, 'name': 'Dora', 'language': 'С#'},
{'id': 5, 'name': 'Dora', 'language': 'Java'},
{'id': 6, 'name': 'Dars', 'language': 'Python'}];
how can I to do a list of dictionary but to unit key and value?
I want to get like this:
list = [{'id': 1, 'name': 'Adel', 'language':['С#','Python']},
{'id': 5, 'name': 'Dora', 'language': ['С#','Java']},
{'id': 6, 'name': 'Dars', 'language': 'Python'}];
I tried this:
mapping = {}
for d in qs:
try:
entry = mapping[d['id']] # raises KeyError
entry['language__name'].append(d['language__name']) # raises AttributeError
except KeyError:
mapping[d['id']] = d
except AttributeError:
entry['language__name'] = [entry['language__name'], d['language__name']]
print(list(mapping.values()))
You can iterate over lst and create a dictionary out where the keys correspond to "id" values in the dicts in lst and the values are dicts. In each iteration, check if the value under "language" key is a list or not and append to the list if it's a list, create a list, if not. Finally, pass the values of out to a list constructor for the final outcome.
out = {}
for d in lst:
if d['id'] in out:
if isinstance(out[d['id']]['language'], list):
out[d['id']]['language'].append(d['language'])
else:
out[d['id']]['language'] = [out[d['id']]['language'], d['language']]
else:
out[d['id']] = d
out = list(out.values())
Output:
[{'id': 1, 'name': 'Adel', 'language': ['С#', 'Python']},
{'id': 5, 'name': 'Dora', 'language': ['С#', 'Java']},
{'id': 6, 'name': 'Dars', 'language': 'Python'}]
How can I print a list without the first square brackets?
[[{'id': '5b0cecebc15ae360393438c2', 'owner': {'id': '58ebd0b12c593e5253505ad4'}, 'linked_id': None, 'type': 'product', 'name': 'Трансформаторное масло Т-1500у'}]]
At the same time, it is necessary to preserve its essence of the list.
So that the parser can read the id.
items = response['data']
usr_ids = items[i]["owner"]["id"]
Simply print the first item of the list
lst = [[{'id': '5b0cecebc15ae360393438c2', 'owner': {'id': '58ebd0b12c593e5253505ad4'}, 'linked_id': None, 'type': 'product', 'name': 'Трансформаторное масло Т-1500у'}]]
print(lst[0])
I've been stuck on this for hours.. I want to retrieve only ONE individuals keys and values from a dictionary that is nested inside of a list.
GAMERS = [{
'name': 'Fatboi',
'parent': 'Dick Van Dyke',
'game': 'Dark Souls 3',
'weight': '420 lbs'
},
{
'name': 'Justin',
'parent': 'Heather Blueberry',
'game': 'Tetris',
'weight': '180 lbs'
},
{
'name': 'jerkhead',
'parent': 'none',
'games': 'Hello Kitty',
'weight': '240 lbs'
},{
'name': 'Tumor',
'parent': 'Jack Black',
'games': 'Trying to live',
'weight': '150 lbs'
}]
So for instance I want to get Justins information printed only, nobody elses. Any insights?
You can pass the key which you want and push it to separate list.
GAMERS = [{
'name': 'Fatboi',
'parent': 'Dick Van Dyke',
'game': 'Dark Souls 3',
'weight': '420 lbs'
},
{
'name': 'Justin',
'parent': 'Heather Blueberry',
'game': 'Tetris',
'weight': '180 lbs'
},{
'name': 'jerkhead',
'parent': 'none',
'games': 'Hello Kitty',
'weight': '240 lbs'
}]
def get_key_pair_list(input_dict, key):
new_list = []
for item in input_dict:
my_dict = {}
if key in item.keys():
my_dict[key] = item[key]
new_list.append(my_dict)
return new_list
print(get_key_pair_list(GAMERS, 'name'))
Output:
[{'name': 'Fatboi'}, {'name': 'Justin'}, {'name': 'jerkhead'}]
Comprehensive way:
key = 'name'
my_list = [{key, item[key]} for item in GAMERS if key in item.keys() ]
print(my_list)
output:
[{'name', 'Fatboi'}, {'name', 'Justin'}, {'name', 'jerkhead'}]
You want to filter the list and grab the first value that matches a predicate. Make sure to handle the case where the item doesnt exist!
filtered_info = (
item for item in GAMERS if item['name'] == 'Justin'
)
justin_info = next(filtered_info, None)
if justin_info is not None:
print(justin_info)
How to split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary?
For example:
lst = [{item:'321,121,343','name':'abby','amount':'400'},{item:'111,222,333','name':'chris','amount':'500'}]
I'd like each part of the item key-value pair to be in its own dictionary
Desired_List = [{item:'321','name':'abby','amount':'400'},{item:'121','name':'abby','amount':'400'},{item:'343','name':'abby','amount':'400'},{item:'111','name':'chris','amount':'500'},{item:'222','name':'chris','amount':'500'},{item:'333','name':'chris','amount':'500'}]
I've tried this with no luck:
[li.update({li['item']:spl}) for li in lst for spl in li['item'].split(',')]
return Li
def unpack_dict(d, field, unpack):
packed = d.pop(field)
for item in unpack(packed):
result = d.copy()
result[field] = item
yield result
lst = [
{'item':'321,121,343','name':'abby','amount':'400'},
{'item':'111,222,333','name':'chris','amount':'500'}
]
new_lst = [
ud
for d in lst
for ud in unpack_dict(d, "item", lambda item: item.split(","))
]
gives new_lst =
[
{'amount': '400', 'item': '321', 'name': 'abby'},
{'amount': '400', 'item': '121', 'name': 'abby'},
{'amount': '400', 'item': '343', 'name': 'abby'},
{'amount': '500', 'item': '111', 'name': 'chris'},
{'amount': '500', 'item': '222', 'name': 'chris'},
{'amount': '500', 'item': '333', 'name': 'chris'}
]
Here is a working script:
lst = [{'item':'321,121,343','name':'abby','amount':'400'}, {'item':'321,121,343','name':'chris','amount':'500'}]
new_list = [{'item':j, 'name': i['name'], 'amount': i['amount']} for i in lst for j in i['item'].split(',')]
>>> print new_list
[{item:'321','name':'abby','amount':'400'},{item:'121','name':'abby','amount':'400'},{item:'343','name':'abby','amount':'400'},{item:'111','name':'chris','amount':'500'},{item:'222','name':'chris','amount':'500'},{item:'333','name':'chris','amount':'500'}]
Demo: http://repl.it/RaE