Home > database >  create new dictionary based on keys and split the dictionary values
create new dictionary based on keys and split the dictionary values

Time:05-13

I am relatively new to python programming. I was trying some challenges in online to thorough my programming skills. I got stuck with the below code. Please someone help here.

ress = {'product': ['Mountain Dew Spark', 'pepsi'], 'quantity': ['7', '5']}
prods_list = []
prods_dict = {}
for k , v in ress.items():
    if "product" in k:
        if len(ress['product']) > 1:
            entity_names = {}
            entity_list = []
        for i in range(len(ress['product'])):
            prod = "product_"   str(i)
            entity_names['product'] = ress['product'][i]
            entity_names['quantity'] = ress['quantity'][i]
            entity_list.append(entity_names)
            prods_dict[prod] = entity_list
prods_list.append(prods_dict)
print(prods_list)

i am expecting output as below

Expected output:
[{"product_0":

{"quantity" : "7",
"product" : "mountain dew spark"}
},
{"product_1" : {
"quantity" : "5",
"product" : "pepsi"
}}]


Actual output:
[{'product_0': [{'product': 'pepsi', 'quantity': '5'},
{'product': 'pepsi', 'quantity': '5'}],
'product_1': [{'product': 'pepsi', 'quantity': '5'},
{'product': 'pepsi', 'quantity': '5'}]}]

Please note i want my code work for single values as well like ress = {'product': ['Mountain Dew Spark'], 'quantity': ['7']}

CodePudding user response:

This is one way you can achieve it with regular loops:

ress = {'product': ['Mountain Dew Spark', 'pepsi'], 'quantity': ['7', '5']}

prods_list = []

for key, value in ress.items():
    for ind, el in enumerate(value):
        prod_num = 'product_'   str(ind)
        # If this element is already present
        if (len(prods_list) >= ind   1):
            # Add to existing dict
            prods_list[ind][prod_num][key] = el
        else:
            # Otherwise - create a new dict
            prods_list.append({ prod_num : { key : el } })

print(prods_list)

The first loop goes through the input dictionary, the second one through each of its lists. The code then determines if a dictionary for that product is already in the output list by checking the output list length. If it is, the code simply appends new inner dict for that product. If it is not - the code creates an outer dict for that product - and an inner one for this particular value set.

CodePudding user response:

Maybe using a list comprehension along with enumerate and zip might be easier:

>>> res = {'product': ['Mountain Dew Spark', 'pepsi'], 'quantity': ['7', '5']}
>>> prods_list = [
...     {f'product_{i}': {'quantity': int(q), 'product': p.lower()}}
...     for i, (q, p) in enumerate(zip(res['quantity'], res['product']))
... ]
>>> prods_list
[{'product_0': {'quantity': 7, 'product': 'mountain dew spark'}}, {'product_1': {'quantity': 5, 'product': 'pepsi'}}]

This assumes that there will be no duplicate product entries. In that case, you would need to use a traditional for loop.

  • Related