2021年3月14日星期日

Is there a more elegant way of writing this in Python - Splitting out a dictionary value into a list of Dictionaries

I am trying to find a more simpler way of splitting a dictionary string value into a dictionary list:

d = [{"name": "Fruit list 1", "fruits": "apple| pear", "cost": "23.56"}, {"name": "Fruit list 2", "fruits": "pineapple| orange| grape", "cost": "10.00"}, {"name": "Fruit list 3", "fruits": "apple| strawberry", "cost": "13.56"}]  

I want to split out the fruits key into a list of dictionaries like:

[{"name": "Fruit list 1", "fruits": [{"value": "apple"}, {"value": "pear"}], "cost": "23.56"}, {"name": "Fruit list 2", "fruits": [{"value": "pineapple"}, {"value": "orange"}, {"value": "grape"}], "cost": "10.00"}, {"name": "Fruit list 3", "fruits": [{"value": "apple"}, {"value": "strawberry"}], "cost": "13.56"}]  

I have written this as:

    import ast        for line in d:          f = ""          for fruit in line["fruits"].split("|"):              if f == "":                  f = "{\"value\": \"" + fruit.strip() + "\"}"              else:                  f = f + ", {\"value\": \"" + fruit.strip() + "\"}"          line["fruits"] = [ast.literal_eval(f)]  

Just looking for a more elegant solution, thank you in advance for your help.

https://stackoverflow.com/questions/66631117/is-there-a-more-elegant-way-of-writing-this-in-python-splitting-out-a-dictiona March 15, 2021 at 08:56AM

没有评论:

发表评论