Home > Enterprise >  Modify keys and values of a dict in a list of dicts (python 3)
Modify keys and values of a dict in a list of dicts (python 3)

Time:10-25

I have a csv file (uneditable), which looks like this:

fruit,price,amount
apple,1,2
banana,3,4
kiwi,5,6

that I've read into a list of dicts:

goodies = []
with open(blabla) as file:
    reader = csv.DictReader(file)
    for fruit in file:
        goodies.append(fruit)

It looks like this:

goodies = [{'fruit' : 'apple', 'price' : '1', 'amount':'2'}, {'fruit' : 'banana', 'price' : '3', 'amount':'4'}, {'fruit' : 'kiwi', 'price' : '5', 'amount':'6'}]

What I actually need:

fruit = [{'apple': [1, 2]}, {'banana': [3, 4]}, {'kiwi': [5, 6]}]

The goal is to be able to compare the values with another list of values and receive the fruit it's referring to, kinda like:

check = [5, 6]
# compare with all fruit
Output: kiwi

I can't tell if I can read the file better or have to fix it somehow afterwards, so any help would be appreciated.

What I have tried:

  1. Using goodies to make a new list (don't know why this won't format as code, sorry!)

    fruit = [] for i in range(len(goodies)): f = list(goodies[i].values()) fruit.append(f)

Resulting in:

[['apple', '1', '2'], ['banana', '3', '4'], ['kiwi', '5','6']]
  1. Taking the above and trying a tuple:

    fruit01 = {tuple(sub[:1]): tuple(sub[1:]) for sub in fruit}

Resulting in (why are those funny commas there?):

{('apple',):('1','2'), ('banana',):('3','4'), ('kiwi',):('5','6')}

Disclaimer: this is my first encounter with python and first question here, lemme know if I'm doing it wrong :)

CodePudding user response:

Use some dictionary creation:

goodies = []
with open(blabla) as file:
    reader = csv.DictReader(file)
    for fruit in file:
        goodies.append({fruit['fruit']: [fruit[x] for x in fruit if x != 'fruit']})
  • Related