Psionman
Psionman

Reputation: 3719

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?

Upvotes: 0

Views: 74

Answers (3)

lllrnr101
lllrnr101

Reputation: 2343

{(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.

Upvotes: 0

Tomerikoo
Tomerikoo

Reputation: 19430

You can use islice to avoid the if check:

from itertools import islice

dict_2 = {str(item): 0 for item in range(skip)}

for key, item in islice(dict_1.items(), skip, None):
    dict_2[key] = item

Alternatively, combine both options to one loop, using enumerate:

for i, (key, value) in enumerate(dict_1.items()):
    if i < skip:
        dict_2[str(i)] = 0
    else:
        dict_2[key] = value

Upvotes: 1

Daniel Hao
Daniel Hao

Reputation: 4981

Not sure this is what you have in mind (did not get your confirm), try to make minimum change to your original code, and keep the orig. keys intact as well:

skip = 3

dict_2 = dict_1.copy()   # create a new copy for updating


for k, v in dict_1.items():
    if skip > 0:
        dict_2[k] = 0
    skip -= 1


print(dict_2)

Upvotes: 0

Related Questions