Search code examples
pythondictionarypercentage

How could I change all values in a dictionary by a percentage?


Is there a easy way to change every dictionary value by a percentage or do I have to loop through them all and change them by a percentage lets say 2%. So the first one that is 100 would change to 102% but the second that's 1000 would change by 20 so 1020.


Solution

  • my_dict = {"a": 100, "b": 1000, "c": 500}
    # Use dictionary comprehension to increase each value by 2%
    my_dict = {key: value * 1.02 for key, value in my_dict.items()}
    print(my_dict)
    

    Or use the Pandas library:

    import pandas as pd
    
    my_dict = {"a": 100, "b": 1000, "c": 500}
    df = pd.DataFrame(list(my_dict.items()), columns=['key', 'value'])
    
    # Increase each value by 2%
    df['value'] *= 1.02
    
    my_dict = pd.Series(df.value.values, index=df.key).to_dict()
    print(my_dict)