#capgemini

Поделиться
HTML-код
  • Опубликовано: 27 июл 2024
  • #capgemini #interview #question
    Using Dictionary Data Structure to increment all values without creating a new dictionary.
    Increment values in a Dictionary without creating a new Dictionary
    To increment values in a dictionary without creating a new dictionary, you can iterate through the dictionary and directly modify its values. Here are two different scenarios to achieve this depending on the requirement.
    Scenario 1:
    Increment all values with the same number.
    If the dictionary has integer values and you want to increment all of them by a certain amount. Let's create a dictionary named Fruits consisting of different fruits and their price per piece - increment all values by 1.
    Fruits={ 'Orange':0.60,'Apple':0.70,'Grapes':0.30}
    for fruit, price in Fruits. items():
    Fruits[fruit]= price+1
    print(Fruits)
    Scenario 2:
    Increment values with different numbers.
    If you have a dictionary and want to increment all values for a specific key, put conditions accordingly. Let's create a dictionary named Fruits consisting of different fruits and their price per piece - increment the values according to the fruit. The price of an orange is increased by 1, an apple is increased by 2, and grapes by 3.
    Fruits={ 'Orange':0.60,'Apple':0.70,'Grapes':0.30}
    for fruit, price in Fruits. items():
    if fruit=='Orange':
    Fruits[fruit]=price+1
    elif fruit=='Apple':
    Fruits[fruit]=price+2
    else:
    Fruits[fruit]=price+3
    print(Fruits)
    Kindly #like #share #subscribe my channel.

Комментарии • 1