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

Rustom Mody rustompmody at gmail.com
Sun Apr 1 13:03:09 EDT 2018


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]


More information about the Python-list mailing list