1

I am trying to create a function which allows me to have a
dictionary like this :{'Apple': 7,'Pearl: 5, 'strawberry': 3}
using this string: "Apple,2,5;Pearl,3,2;Strawberry,1,2;".

I want to use the numbers on the string as an integer and do the addition process to be the result. However I was trying to split the string into pieces so I can make it an integer

   def cal(Fruitsamount):
        Fruitsamount.split(";")
        dict1 = {Fruitsamount[0:5]: Fruitsamount[5:8]}
        return dict1
    print(cal("Apple,2,5;Pearl,3,2;Strawberry,1,2;"))

I would like to know how can I transform part of the numbers on the string into integers so I can do the addition process

ppwater
  • 2,315
  • 4
  • 15
  • 29
OLearning
  • 23
  • 5
  • Convert str to int with `int(str)`. So `int("123")` creates a int with a value of `123` – TeddyBearSuicide Jun 07 '21 at 00:58
  • 1
    Split each part again by `,`, get `[1:]` to get the list of ints, then [Convert all strings in a list to int](https://stackoverflow.com/q/7368789/2745495) – Gino Mempin Jun 07 '21 at 00:59

4 Answers4

2

You can first split the text on ; which will give the key and values for each item for the dictionary, and then split these values on ,, the first value is the key, and rests are the values for the given key, iterate through each values and type cast the values to the integer, finally calculate the sum of these values. But since your sample string contains ; at the end, you may want to strip it first before proceeding.

def getDict(text):
    result = {}
    text = text.strip(';')
    for row in text.split(';'):
        cols = row.split(',')
        result[cols[0]] = sum(int(i) for i in cols[1:])
    return result

getDict('Apple,2,5;Pearl,3,2;Strawberry,1,2;')
#output: {'Apple': 7, 'Pearl': 5, 'Strawberry': 3}

One-liner solution using lambda, map, and comprehension:

getDict = lambda text: {col[0]:sum(map(int, col[1:])) 
                        for col in map(lambda x: x.split(','), 
                                       (row for row in text.strip(';').split(';')))
                        }
getDict('Apple,2,5;Pearl,3,2;Strawberry,1,2;')
# ooutput: {'Apple': 7, 'Pearl': 5, 'Strawberry': 3}
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
1

You need to iterate over the result of the split by ;. Then, you can construct the dictionary by unpacking the split by , and summing over the numbers.

def cal(Fruitsamount):
    d = {}
    for item in Fruitsamount.strip(";").split(";"):
        k, *vs = item.split(",")
        d[k] = sum(map(int, vs))
    return d

print(cal("Apple,2,5;Pearl,3,2;Strawberry,1,2;"))
{'Apple': 7, 'Pearl': 5, 'Strawberry': 3}
iz_
  • 15,923
  • 3
  • 25
  • 40
1

You can transform them to integers using int.

def to_dict(inventory):
    items = inventory.split(";")
    items = [item.split(',') for item in items]
    keys = [item[0] for item in items]
    values = [sum(map(int, item[1:])) for item in items]
    return dict(zip(keys, values))
Yohan F
  • 11
  • 1
-1

I tried to re-implement the code to make it easier to read, after you split by ";" and get each key-value pair you have to split by comma and get first element as key, all of the rest value as values. Here is my implementation:

x = "Apple,2,5;Pearl,3,2;Strawberry,1,2;"


def cal(string):
  dict_keys = string.split(';')

  result_dict = dict()
  for element in dict_keys:
    key_value = element.split(',')
    key = key_value[0]
    result_dict[key] = [int(val) for val in list(key_value[1:])]

 
  return result_dict


print(cal("Apple,2,5;Pearl,3,2;Strawberry,1,2;"))

Simply use int() to every value in a list could do the work.

林彥良
  • 82
  • 11