0

If i have a dictionary like:

d = {'word': {'word1': '1', 'word2': '-1', 'word3': '2'}}

is there any way in which i can detect which string contains a number and turn that string into the corresponding int representation of that number?

edit: omg i finally solved it, thank you so much! (unfortunately i can't upvote)

  • You could test it with a regular expression. Or you could just call `int` regardless but `pass` on any `ValueError` exception. – alani Oct 26 '21 at 15:04
  • Using [`int`](https://docs.python.org/3/library/functions.html#int) would be a start. Did you forget to post the code you tried to solve this issue with along with the error you got? How about researching this issue before asking? – Jab Oct 26 '21 at 15:05
  • sorry, i actually researched a lot and tried many times in different approaches, but as i'm new to programming my methods are really chaotic and not organised enough for me to be able to explain properly what i did until now. – christmas.tree Oct 26 '21 at 15:08

3 Answers3

0

One approach:

d = {'word': {'word1': '1', 'word2': '-1', 'word3': '2'}}


def nested_set(data):
    for key, value in data.items():

        if isinstance(value, dict):
            nested_set(value)
        elif isinstance(value, str):
            try:
                data[key] = int(value)
            except ValueError:
                pass


nested_set(d)
print(d)

Output

{'word': {'word1': 1, 'word2': -1, 'word3': 2}}
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
0

A recursive version of map for arbitrarily nested dictionaries (and list/tuples/sets/sequences):

def map_nested(fnc, obj):
    if isinstance(obj, dict):
        return {k: map_nested(fnc, v) for k, v in obj.items()}
    if not isinstance(obj, str):
        try:
            return type(obj)(map_nested(fnc, x) for x in obj)
        except TypeError:
            pass
    try: 
        return fnc(obj)
    except:
        return obj

map_nested(int, {'word': {'word1': '1', 'word2': '-1', 'word3': '2'}})
# {'word': {'word1': 1, 'word2': -1, 'word3': 2}}
map_nested(int, {'word': {'word1': '1', 'word2': '-1', 'word3': ['2', "5"]}})
# {'word': {'word1': 1, 'word2': -1, 'word3': [2, 5]}}
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

If by assumption your dict is in the form of {'key': {'key': 'integer'}, 'key': {'key': 'integer'}} You can use the following:

dct = {...}
result = {key: dict(zip(d, map(int, d.values))) for key, d in dct.items()}

Or if your dict is just as simple as your example then the following will suffice:

result = {'word': dict(zip(d, map(int, d.values)))}
Jab
  • 26,853
  • 21
  • 75
  • 114