Home > Mobile >  Change certain values in a list to integers? Python
Change certain values in a list to integers? Python

Time:04-25

I have created this dictionary from a file. It has a key with a list of values. The elements in the list are all strings. I want to convert the elements at the indices 1 through 3 to integers.

Here is one key:value that I have in my dictionary.

{'Youngstown': ['OH', '4110', '8065', '115436'].....}

I want to leave the 'OH' as a string and convert all the other elements to integers.

Like this:

{'Youngstown': ['OH', 4110, 8065, 115436].....}

This is the code that I have so far.

d3 = {}
for k,v in d2.items():
    for i in v:
        for v in range(1,3):
            d3[k] = int(v)

print(d3)

However, this just gives the following result:

{'Youngstown': 2, ...}

This is in python.

CodePudding user response:

Your issue is that you are overwriting the value of d3[k] each time through your inner for loop (which is also overwriting the v value incorrectly). You need to set up d3[k] as a list, and then append the int values to it. For example:

for k, v in d2.items():
    d3[k] = [v[0]]
    for i in range(1, 4):
        d3[k].append(int(v[i]))

You could also consider using str.isnumeric() to check the values and only convert when that is true. For example:

for k, v in d2.items():
    d3[k] = [int(i) if i.isnumeric() else i for i in v]

That could then be wrapped into a nested comprehension:

d3 = { k : [int(i) if i.isnumeric() else i for i in v] for k, v in d2.items() }

CodePudding user response:

Given:

di={'Youngstown': ['OH', '4110', '8065', '115436'],'Columbus':['OH','1','2','3']}

You can write a little function that uses try / except to convert the ints if it is possible to do so:

def conv(e):
    try:
        return int(e)
    except ValueError:
        return e 
    
di={k:[conv(e) for e in v] for k,v in di.items()}

>>> di
{'Youngstown': ['OH', 4110, 8065, 115436], 'Columbus': ['OH', 1, 2, 3]}

CodePudding user response:

To change in a list in place, you can assign to a slice of the list. This makes a readable simple loop:

d3 = {
    'Youngstown': ['OH', '4110', '8065', '115436'],
    'Anchorage': ['AK', '5432', '1232', '350492']
}

for l in d3.values():
    l[1:] = map(int, l[1:])

After this, d3 will look like:

{'Youngstown': ['OH', 4110, 8065, 115436],
 'Anchorage': ['AK', 5432, 1232, 350492]}

If there are elements beyond index 3 that you don't want to touch, you can define the final bound of the slice:

l[1:4] = map(int, l[1:4])

CodePudding user response:

This should do what you want:

d3 = {}
for k,v in d2.items():
    d3[k] = [v[0]]   [int(n) for n in v[1:]]

For each element of the dictionary, it constructs a new list, copying the first element unchanged and applying int() to the remaining elements. It then stores the result in the new dict.

Example: With the following value for d2:

d2 = {'Youngstown': ['OH', '4110', '8065', '115436'],
      'foo': ['x', '10', '20', '30']}

it produces the following for d3:

{'Youngstown': ['OH', 4110, 8065, 115436], 'foo': ['x', 10, 20, 30]}
  • Related