Home > other >  remove last character from dict value python
remove last character from dict value python

Time:11-16

I have got a dict:

base = [
    {'num': 10, 'bet': '100EUR'},
    {'num': 22, 'bet': '10EUR'},
    {'num': 10, 'bet': '210EUR'},
    {'num': 11, 'bet': '100EUR'},
    {'num': 8, 'bet': '50EUR'},
    {'num': 10, 'bet': '10EUR'},
    {'num': 8, 'bet': '30EUR'},
    {'num': 32, 'bet': '10EUR'}]

I am trying to remove last 3 symbols from all 'bet' values and make the result from str to int- so my base to become like this:

base = [
        {'num': 10, 'bet': 100},
        {'num': 22, 'bet': 10},
        {'num': 10, 'bet': 210},
        {'num': 11, 'bet': 100},
        {'num': 8, 'bet': 50},
        {'num': 10, 'bet': 10},
        {'num': 8, 'bet': 30},
        {'num': 32, 'bet': 10}]

How to do this? Thanks!

CodePudding user response:

Really you have a list of dictionaries; you can directly change the values in them by iterating and then by-name

for subdict in base:
    subdict["bet"] = int(subdict["bet"].replace("EUR", ""))

this is fragile on purpose to discover bad values in your list (raising ValueError for non-int keys if .replace() fails or you have some other structure); you can (for example) also extend this to other currencies by detecting a substring like "USD" subdict["bet"] before doing a conversion (though you would also want to convert the currency)

CodePudding user response:

Use a list comprehension and slice the bet key and convert to int

base = [{'num': b['num'], 'bet': int(b['bet'][:-3])}
        for b in base]
print(base)

CodePudding user response:

Update the values in place by slicing the values and converting to int:

for d in base:
    d['bet'] = int(d['bet'][:-3])

Output:

[{'num': 10, 'bet': 100},
 {'num': 22, 'bet': 10},
 {'num': 10, 'bet': 210},
 {'num': 11, 'bet': 100},
 {'num': 8, 'bet': 50},
 {'num': 10, 'bet': 10},
 {'num': 8, 'bet': 30},
 {'num': 32, 'bet': 10}]
  • Related