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'}}
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.
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!"}
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.
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.
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': {}}
def f(d):
new = {}
for k,v in d.items():
if isinstance(v, dict):
v = f(v)
new[str(k)] = v
return new
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With