I am utilising the fact that for python >= 3.7 elements in a dictionary are retrieved in the order of insertion.
I want to create a dict where the first skip items contain zero; after that, they take the relevant values from a master dict
dict_1 = {
'a1' : 11,
'a2' : 12,
'a3' : 13,
'b1' : 14,
'b2' : 15,
'c1' : 16,
}
skip = 3
dict_2 = {}
for item in range(skip):
dict_2[str(item)] = 0
index = 0
for key, item in dict_1.items():
index += 1
if index > skip:
dict_2[key] = item
print(dict_2)
{'0': 0, '1': 0, '2': 0, 'b1': 14, 'b2': 15, 'c1': 16}
For the avoidance of doubt, the keys in dict_2 are different from the keys in dict_1 for items < skip.
This does what I want, but it is inelegant. Is there a more pythonic approach I could take?
question from:
https://stackoverflow.com/questions/65923635/is-there-a-more-pythonic-way-of-handling-dictionaries 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…