Home > Software design >  How to update a list of dictionaries from a user input?
How to update a list of dictionaries from a user input?

Time:08-20

I'm new to Python and working on a task where I need to update a list of dictionaries from a customer input.

I have a list as follows:

drinks_info = [{'Pepsi': 2.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}]

If the user inputs: Pepsi: 3.0, Sprite: 2.50

Then the list should update to: [{'Pepsi': 3.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}], {'Sprite': 2.50}]

Any help is appreciated. Thanks in advance.

CodePudding user response:

  1. We can use a function to update list based on user inputs. This function would ask user for each list item separately.
def update_drinks_info(drinks_info):
    for drink in drinks_info:
        for key, value in drink.items():
            print(key, value)
            new_price = input("Enter new price for "   key   ": ")
            if new_price != "":
                drink[key] = float(new_price)

    return drinks_info

This function asks user to enter the new price for the specified item, if user presses Enter, then the price stays same without any additional input.

  1. We can use a function to update list based on user specified keys and values.
def update_drinks_info(drinks_info, drink, price):
    index = 0
    for i in range(len(drinks_info)):
        if drink in drinks_info[i]:
            index = i
            break

    drinks_info[index] = {drink: price}
    return drinks_info


def split_input(input):
    drinks = input.split(", ")
    for drink in drinks:
        drink = drink.split(":")
        drink[1] = float(drink[1])
        update_drinks_info(drinks_info, drink[0], drink[1])

Using split_input function, we are dividing user input to separate arrays and update the drinks info using the specified drink and price.

For example:

split_input(input("Enter drink and price: "))

with the example input of Pepsi: 3.0, Sprite: 2.50 is going to update the price of both items.

CodePudding user response:

You could try this:

def update_drinks(drinks_info, query_string):
    query_list = query_string.split(":")
    updated = False
    for drink_items in drinks_info:
        for values in drink_items.keys():
            if values == query_list[0].strip():
                updated = True
                drink_items[query_list[0].strip()] = float(query_list[1].strip())

    if not updated:
        drinks_info.append({query_list[0].strip(): float(query_list[1].strip())})



if __name__ =="__main__":
    drinks_info = [{'Pepsi': 2.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}]
    for _ in range(2):
        query_string =input()
    # the string is given in the format DrinkName : Value
        update_drinks(drinks_info, query_string)

    print("The updated drink list")
    print(drinks_info)

CodePudding user response:

  1. This may be easily implemented if transformed into a dictionary format;
  2. And then get the user updates also in dictionary format;
  3. Then update the drinks dictionary as was transformed;
  4. Finally convert it back to the original list format
drinks_info = [{'Pepsi': 2.0}, {'Coke': 2.0}, {'Solo': 2.50}, {'Mt Dew': 3.0}]
drinks_info_dict = {item: value for drink in drinks_info for item, value in drink.items()}

user_input = "Pepsi: 3.0, Sprite: 2.50"
updates = {details.split(":")[0].strip(): float(details.split(":")[1]) for details in user_input.split(",")}

drinks_info_dict.update(updates)

drinks_info = [{item: value} for item, value in drinks_info_dict.items()]
print(drinks_info)

Output:

[{'Pepsi': 3.0}, {'Coke': 2.0}, {'Solo': 2.5}, {'Mt Dew': 3.0}, {'Sprite': 2.5}]
  • Related