0

I have a dictionary of lists, each list has 3 elements, i want to convert the 2nd and 3rd element to ints from strings

dict = {1:['string', '2', '3',],
        2:['string', '2', '3',],
        3:['string', '2', '3',],}

to become:

dict = {1:['string', 2, 3,],
        2:['string', 2, 3,],
        3:['string', 2, 3,],}

Thank you

2 Answers 2

3

Firstly, don't name your dictionaries dict, as it's a reserved keyword and you don't wanna overwrite it.

Coming to your solution.

d = {
    1: ['string', '23', '3'],
    2: ['string', '2', '3'],
    3: ['string', '2', '3'],
}


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

Will give you an output of:

{   
    1: ['string', '23', '3'], 
    2: ['string', '2', '3'], 
    3: ['string', '2', '3']
}
{
    1: ['string', 23, 3], 
    2: ['string', 2, 3], 
    3: ['string', 2, 3]
}
Sign up to request clarification or add additional context in comments.

1 Comment

Caution: This solution will also convert the first element of the list to an integer when it contains only digits! This was not requested by OP
0

If you dictionary has many elements you might not want to create a second dictionary in memory, but modify the existing one in-place:

data = {
    1: ['string', '2', '3'],
    2: ['string', '2', '3'],
    3: ['string', '2', '3'],
}

for v in data.values():
    v.append(int(v.pop(1)))
    v.append(int(v.pop(1)))

print(data)

Output:

{1: ['string', 2, 3], 2: ['string', 2, 3], 3: ['string', 2, 3]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.