Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - Is there a more Pythonic way of handling dictionaries?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
{(xy[0] if i>=skip else str(i)):(xy[1] if i>=skip else 0)  for i,xy in enumerate(iter(dict_1.items()))}

However let us remember that Simple is better than complex and Readability counts.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...