Reputation: 23
I am trying to make it so whenever the value in my dictionary is 'A9', the key:value pairs after 'A9' become 'a0' and it iterates all over again until 'a9' which I would then like to change to 'B0', etc.
My expected output:
{'0000': 'A0', '0001': 'A1', '0002': 'A2', '0003': 'A3', '0004': 'A4', '0005': 'A5', '0006': 'A6', '0007': 'A7', '0008': 'A8', '0009': 'A9', '0010': 'a0', '0011': 'a1', '0012': 'a2', '0013': 'a3', '0014': 'a4', '0015': 'a5', '0016': 'a6', '0017': 'a7', '0018': 'a8', '0019': 'a9', '0020':'B0', '0021':'B1'}
My current code:
ustr = (['%.4d' % i for i in range(0, 22)])
d2 = {x:f'A{i+0}' for i, x in enumerate(sorted(set(ustr)))}
print(d2)
for k, v in d2.items():
print(v)
if v == 'A9':
v = {x:f'a{i+0}' for i, x in enumerate(sorted(set(ustr)))}
print(v)
This output I'm receiving is overriding my dictionary. I know why. I'm telling the if statement to replace all the values of the string with 'a0'. I just don't know how to write the code to specify that after 'A9' that it continues with 'a0'.
Upvotes: 0
Views: 137
Reputation: 16505
Python dictionaries are unordered, so there is no concept of "before" that specific key or "after".
The sorting you are doing with {x:f'a{i+0}' for i, x in enumerate(sorted(set(ustr)))}
has no effect once the dict
is created.
Maybe consider using a OrderedDict
(it is in the standard lib).
Note: specific Python implementations (or versions) may keep an iteration order, but it is not garanteed in the language specifications.
Apprently there is a garanteed order starting in Python 3.7
:
iter(dictview)
[...]
Changed in version 3.7: Dictionary order is guaranteed to be insertion order.
Upvotes: 0
Reputation: 1604
Are you trying to do something like this?
input_dict = {'0000': 'A0', '0001': 'A1', '0002': 'A2', '0003': 'A3', '0004': 'A4', '0005': 'A5', '0006': 'A6', '0007': 'A7', '0008': 'A8', '0009': 'A9', '0010': 'a0', '0011': 'a1', '0012': 'a2', '0013': 'a3', '0014': 'a4', '0015': 'a5', '0016': 'a6', '0017': 'a7', '0018': 'a8', '0019': 'a9', '0020':'B0', '0021':'B1'}
alphabet = ['A', 'B', 'C', 'D', 'E', "..."]
numbers = range(10)
dict(zip(input_dict.keys(), [f"{letter}{num}" for letter in alphabet for num in numbers]))
output:
>>>
{'0000': 'A0',
'0001': 'A1',
'0002': 'A2',
'0003': 'A3',
'0004': 'A4',
'0005': 'A5',
'0006': 'A6',
'0007': 'A7',
'0008': 'A8',
'0009': 'A9',
'0010': 'B0',
'0011': 'B1',
'0012': 'B2',
'0013': 'B3',
'0014': 'B4',
'0015': 'B5',
'0016': 'B6',
'0017': 'B7',
'0018': 'B8',
'0019': 'B9',
'0020': 'C0',
'0021': 'C1'}
You can add an extra row of A's at the beginning pretty easily. But I wasn't sure if you wanted that or if that was a typo.
Upvotes: 1