简体   繁体   中英

string representation of dictionary without quotes in values

I am trying to create a string that can be evaluated to a dictionary such as:

'{"key1": val1, "key2": val2}'

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})

This mostly works except instead of val1 I get 'val1' . I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.

Not pretty, but accomplishes what you're looking for:

args = ["key1", "key2"]

your_attempt = str({key: "val%d" % i for i, key in enumerate(args)})
# outputs: "{'key2': 'val1', 'key1': 'val0'}"

your_attempt.replace("': '","': ").replace("', '",", '").replace("'}","}")
# outputs: "{'key2': val1, 'key1': val0}"

You could use eval() if this is what you are after:

val1 = "one"
val2 = "two"
test = '{"key1": val1, "key2": val2}'
test_dict = eval(test)
print(test_dict)
# {'key1': 'one', 'key2': 'two'}

For the sake of standardization, I would suggest using the builtin json library to encode and decode your info strings.

>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]

The json module plays nice with request, pickle, etc. and can help you avoid headache and mistakes by implementing the formatting protocols for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM