I receive this dict in my system, with string values, and I need to organize it in a custom way.
kafka_data = {
"flush_size": "1000",
"branch": "develop",
"cluster": "analytics",
"system": "ft7",
"topic_name": "topic_test",
"compatibility": "backward"
}
I found some infos and ways to organize elements, but in lists (not dicts) or in dicts (but with int/numbers).
The expected output would be like this:
kafka_data_expected = {
"topic_name": "topic_test",
"system": "ft7",
"cluster": "analytics",
"branch": "develop",
"compatibility": "backward",
"flush_size": "1000",
}
CodePudding user response:
If you simply recreate the dictionary:
kafka_data = {
"flush_size": "1000",
"branch": "develop",
"cluster": "analytics",
"system": "ft7",
"topic_name": "topic_test",
"compatibility": "backward"
}
kafka_data_expected = {k: kafka_data[k] for k in (
'topic_name', 'system', 'cluster', 'branch', 'compatibility', 'flush_size')}
print(kafka_data_expected)
Result:
{'topic_name': 'topic_test', 'system': 'ft7', 'cluster': 'analytics', 'branch': 'develop',
'compatibility': 'backward', 'flush_size': '1000'}
Dictionaries in Python have maintained insertion order since 3.7 and in practice already did so in CPython 3.6, so the above should work in those versions of Python. For older versions, you'll need the OrderedDict
from collections
.
Having said that - you could still consider using OrderedDict
if you want to be very clear about your intentions, and want your code to be even more future-proof.