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

Chris Angelico rosuav at gmail.com
Sun Apr 1 13:13:15 EDT 2018


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



More information about the Python-list mailing list