Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert nested dictionary keys to strings?

original dictionary keys are all integers. How can I convert all the integer keys to strings using a shorter approach?

original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}

result = {}
for key in original:
    if not key in result:
        result[str(key)]={}
    for i, value in original[key].items():
        result[str(key)][str(i)] = value
print result 

prints:

{'1': {}, '2': {'202': 'TwoZeroTwo', '101': 'OneZeroOne'}}
like image 303
alphanumeric Avatar asked Jan 25 '17 04:01

alphanumeric


People also ask

How do you flatten nested dictionary?

Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. For Python >= 3.3, change the import to from collections.

Can dictionary keys be strings?

The keys of a dictionary can be any kind of immutable type, which includes: strings, numbers, and tuples: mydict = {"hello": "world", 0: "a", 1: "b", "2": "not a number" (1, 2, 3): "a tuple!"}

How do I turn a dict into a string?

To convert a dictionary to string in Python, use the json. dumps() function. The json. dumps() is a built-in function in json library that can be used by importing the json module into the head of the program.

Can Python dictionary keys be strings?

Second, a dictionary key must be of a type that is immutable. For example, you can use an integer, float, string, or Boolean as a dictionary key. However, neither a list nor another dictionary can serve as a dictionary key, because lists and dictionaries are mutable.


2 Answers

Depending on what types of data you have:

original = {1:{},2:{101:"OneZeroOne",202:"TwoZeroTwo"}}
result= json.loads(json.dumps(original))
print(result)

prints:

{'2': {'101': 'OneZeroOne', '202': 'TwoZeroTwo'}, '1': {}}
like image 112
Stephen Rauch Avatar answered Nov 03 '22 18:11

Stephen Rauch


def f(d):
    new = {}
    for k,v in d.items():
        if isinstance(v, dict):
            v = f(v)
        new[str(k)] = v
    return new
like image 20
wwii Avatar answered Nov 03 '22 19:11

wwii