ThatRiddimGuy
ThatRiddimGuy

Reputation: 391

Converting string values inside a dictionary to int

I have a dictionary of dictionaries as follows:

MyDict = {'A1': {'B1': '1', 'B2' : '2'}, 'A2': {'B3': '3', 'B4' : '4'}}

How do I convert the values inside the dictionary to int, as my script currently reads these numbers in as strings. I want to use the numbers in calculations.

So it becomes:

MyDict = {'A1': {'B1': 1, 'B2' : 2}, 'A2': {'B3': 3, 'B4' : 4}}

Any help will be appreciated!

Upvotes: 1

Views: 62

Answers (1)

Alec
Alec

Reputation: 1469

You can use a nested dictionary comprehension where you call int() on each of the inner values (represented here by v2):

my_dict = {'A1': {'B1': '1', 'B2' : '2'}, 'A2': {'B3': '3', 'B4' : '4'}}

my_converted_dict = {k1: {k2: int(v2) for k2, v2 in v1.items()}
                                          for k1, v1 in my_dict.items()}

print(my_converted_dict)
# {'A1': {'B1': 1, 'B2': 2}, 'A2': {'B4': 4, 'B3': 3}}

Upvotes: 1

Related Questions