简体   繁体   中英

What's the most pythonic way to build this dictionary?

I want to create a dictionary such that letters in the first row of a QWERTY keyboard are given a value of one, keys in the home row are given a value of zero, and keys in the bottom row are given a value of two.

I wanted to do this is one line, but I can't think of a way to do this.

I know this will do the first row, but is there a way to get all of the rows in a single line?

firstRow = {i:1 for i in "q w e r t y u i o p".split(' ')}

Edit, I thought of this:

keyboardRating = dict({i:1 for i in "q w e r t y u i o p".split(' ')}.items() + {i:0 for i in "a s d f g h j k l".split(' ')}.items() + {i:2 for i in "z x c v b n m".split(' ')}.items())

but I'm looking for something much simpler.

Well, first, there's this neat trick for getting the firstRow :

firstRow = dict.fromkeys('qwertyuiop', 1)

Then we can just write

keys = {}
keys.update(dict.fromkeys('qwertyuiop', 1))
keys.update(dict.fromkeys('asdfghjkl', 2))
keys.update(dict.fromkeys('zxcvbnm,', 3))

Alternatively, you can try something like this:

rows = {1: 'qwertyuiop', 0: 'asdfghjkl;', 2: 'zxcvbnm,.'}
keys = {c:k for k,row in rows.iteritems() for c in row}

Because of the amount of static data involved, I don't recommend trying to put it all on one line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM