How to fill in a dictionary with key and value from a string?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sun Apr 1 23:13:04 EDT 2018
On Sun, 01 Apr 2018 22:24:31 -0400, C W wrote:
> Thank you Steven. I am frustrated that I can't enumerate a dictionary by
> position index.
Why do you care about position index?
> Maybe I want to shift by 2 positions, 5 positions...
Sounds like you are trying to program the Caesar Shift cipher, am I right?
You probably should be manipulating *strings*, not dicts. Do these
examples help?
py> import string
py> letters = string.ascii_lowercase
py> letters
'abcdefghijklmnopqrstuvwxyz'
py> letters[1:] + letters[:1]
'bcdefghijklmnopqrstuvwxyza'
py> letters[5:] + letters[:5]
'fghijklmnopqrstuvwxyzabcde'
py> letters[23:] + letters[:23]
'xyzabcdefghijklmnopqrstuvw'
Slice your strings into the order that you want, then put them in a dict
for fast lookups by character.
> I want to know/learn how to manipulate dictionary with loop and by its
> position location.
Dict entries don't have a position location except by accident, or in
sufficiently new versions of Python, by insertion order.
If you want to process dict entries in a specific order, operate on the
dict in whichever order you want:
ordered_keys = 'azbycxdwevfugthsirjqkplomn'
for k in ordered_keys:
print(mydict[k])
In Python 3.7, dicts will keep their insertion order, so long as you
don't delete any keys.
--
Steve
More information about the Python-list
mailing list