How to fill in a dictionary with key and value from a string?

C W tmrsg11 at gmail.com
Sun Apr 1 20:52:35 EDT 2018


Thank you all for the response.

What if I have myDict = {'a': 'B', 'b': 'C',...,'z':'A' }? So now, the
values are shift by one position.

key:    abcdefghijklmnopqrstuvwxyz
value: BCDEFGHIJKLMNOPQRSTUVWXYZA

Can I fill in a key and its corresponding value simultaneously on the fly?

Something in the following structure.

myDict = {}
for i in range(26):
       myDict[lowercase] = uppercase

Thank you!

On Sun, Apr 1, 2018 at 1:13 PM, Chris Angelico <rosuav at gmail.com> wrote:

> On Mon, Apr 2, 2018 at 3:03 AM, Rustom Mody <rustompmody at gmail.com> wrote:
> > On Saturday, March 31, 2018 at 4:30:04 PM UTC+5:30, bartc wrote:
> >> On 30/03/2018 21:13, C W wrote:
> >> > Hello all,
> >> >
> >> > I want to create a dictionary.
> >> >
> >> > The keys are 26 lowercase letters. The values are 26 uppercase
> letters.
> >> >
> >> > The output should look like:
> >> > {'a': 'A', 'b': 'B',...,'z':'Z' }
> >>
> >> > I know I can use string.ascii_lowercase and string.ascii_uppercase,
> but how
> >> > do I use it exactly?
> >> > I have tried the following to create the keys:
> >> > myDict = {}
> >> >          for e in string.ascii_lowercase:
> >> >              myDict[e]=0
> >>
> >> If the input string S is "cat" and the desired output is {'c':'C',
> >> 'a':'A', 't':'T'}, then the loop might look like this:
> >>
> >>     D = {}
> >>     for c in S:
> >>         D[c] = c.upper()
> >>
> >>     print (D)
> >>
> >> Output:
> >>
> >> {'c': 'C', 'a': 'A', 't': 'T'}
> >
> > As does…
> >>>> {c: c.upper() for c in s}
> > {'a': 'A', 'c': 'C', 't': 'T'} : dict
> >
> > [Recent pythons; not sure when dict-comprehensions appeared]
>
> 3.0, and also backported to 2.7. So go ahead and use 'em.
>
> https://www.python.org/dev/peps/pep-0274/
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>


More information about the Python-list mailing list