There is a large dictionary in which entries are dictionaries of this type:
"Smth": { "name": "Text", "enemies": [ "enemy1", "enemy2", "enemy3" ], "friends": [ "friend1", "friend2", "friend3" ] }, We need to give weight to all values from the enemies and friends , which will always be extracted along with this weight. For example, enemy1 has a weight of 0.4 , and friend3 has a weight of 0.8 . For each value the weight will be specified manually.
How to do it better? So far, I have done only this method:
"enemies": [ ["enemy1", 0.4], ["enemy2", 0.3], ["enemy3", 0.7] ] Is it a better option? Speed is in priority. Thank.
UPD: We need just such a format, because these dictionaries will be written to a .json file.
"enemies": [("enemy1", 0.4), ("enemy2", 0.3)]- Vladimir Gamalyanjsonfile. If I'm not mistaken, there are no tuples, only lists. Forgot to mention. - Newbieenemy1dictionary with aweightfield, which would give the opportunity to add enemies and other properties later. - Vladimir GamalyanWeigthedItem = namedtuple('WeightedItem', 'id weight'), and when saved as json:default=lambda o: list(o) if isinstance(o, WeightedItem) else json.Encoder().default(o). And so "Better" is subjective: if the code does what it wants, simple, readable and works at a speed sufficient in your case, then it is better to try to improve it in other places. Explicitly indicate a specific problem with the code (readability, consumed memory, speed). - jfs