0

I have a Python dictionary with keys that are strings, and values that are lists of numbers which are also strings. I'd like to convert the numbers to int, but am having some trouble. Just to illustrate, I'd like to change:

d = {'a': ['1', '2', '3'], 'b': ['4', '5', '6'], 'c': ['7', '8', '9']}

into

d = {'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
  • You do it the same as any other list. Except in this case the list is named `d[key]` where `key` is a key in your dictionary instead of e.g. `my_list`. What trouble are you having? – Pranav Hosangadi Jan 18 '23 at 03:30
  • 1
    Does this answer your question? [Convert all strings in a list to int](https://stackoverflow.com/questions/7368789/convert-all-strings-in-a-list-to-int) – Pranav Hosangadi Jan 18 '23 at 03:33
  • So I do: for key, value in d: int(value) but then it says there are too many items to unpack. If I just do int(key) it tries to turn the alphabetical characters to ints which isn't what I want and wouldn't work anyways. – winterdiablo Jan 18 '23 at 03:37
  • Then you want to ask [how to iterate over keys and values of a dictionary](https://stackoverflow.com/a/3294899/843953). Note that you can't just convert the strings to ints, you have to _assign those ints back!_. – Pranav Hosangadi Jan 18 '23 at 03:40
  • 1
    This is why it is good to show your attempt: it helps us help you diagnose your actual issue. Please see [ask] and the [question checklist](//meta.stackoverflow.com/q/260648/843953), and how to provide a [mre]. – Pranav Hosangadi Jan 18 '23 at 03:46
  • Rather than being unclear, this should be a duplicate of https://stackoverflow.com/questions/75666408/. – Karl Knechtel May 19 '23 at 02:48

2 Answers2

1

I would have commented this out but unfortunately, I am new to Stack Overflow and don't have enough reputation. But based on @pranav-hosangadi suggestion you can just do it in a single line.

d = {key: list(map(int, value)) for key, value in d.items()}
0

Use the following code.

for key in d.keys():
    d[key] = list(map(int, d[key]))
Gilseung Ahn
  • 2,598
  • 1
  • 4
  • 11