如何一次为dict对象中的多个键分配相同的值?

时间:2017-10-06 15:40:37

标签: python dictionary

这是我的问题:

// get the screen width
var metrics = Resources.DisplayMetrics;
var widthInDp = (int)((metrics.WidthPixels) / metrics.Density);

// this line is very specific, it calculates the real usable space
// in my case, there was padding of 5dp nine times, so subtract it
var space = widthInDp - 9 * 5;

// and in this usable space, I had 7 identical TextViews, so a limit for one is:
var limit = space / days.Length;

// now calculating the text length in dp            
Paint paint = new Paint();
paint.TextSize = myTextView.TextSize;
var textLength = (int)Math.Ceiling(paint.MeasureText(myTextView.Text, 0, myTextView.Text.Length) / metrics.Density);

// and finally formating based of if the text fits (again, specific)
if (textLength > limit)
{
    myTextView.Text = myTextView.Text.Substring(0, myTextView.Text.IndexOf("-"));
}

结果是:

k = "_opqrst_ _ _ _ yzabc_ _ _ _hijklm"
dict_ = dict.fromkeys(zip(string.ascii_lowercase , k))

我希望我的程序显示如下

{'d': 'q', 'e': 'r', 'x': 'k', 'i': '_', 'o': 'b', 'b': 'o', 'm': 'z', 'k': '_',
'j': '_', 'u': 'h', 'n': 'a', 's': '_', 'a': '_', 'w': 'j', 'v': 'i', 'c': 'p',
't': '_', 'z': 'm', 'f': 's', 'l': 'y', 'p': 'c', 'g': 't', 'h': '_', 'y': 'l',
'r': '_', 'q': '_'} 

这意味着{'资本,小字母':' '}

2 个答案:

答案 0 :(得分:0)

您需要构建密钥,然后构建字典:

import string
k = "_opqrst_ _ _ _ yzabc_ _ _ _hijklm"
k_wthout_whites = ''.join([c for c in k if c != ' '])   # removing white space
keys = [','.join(elt) for elt in (zip(string.ascii_uppercase, string.ascii_lowercase))]
dict_ = {key: val for key, val in zip(keys, k_wthout_whites)}
dict_

输出:

{'A,a': '_',
 'B,b': 'o',
 'C,c': 'p',
 'D,d': 'q',
 'E,e': 'r',
 'F,f': 's',
 'G,g': 't',
 'H,h': '_',
 'I,i': '_',
 'J,j': '_',
 'K,k': '_',
 'L,l': 'y',
 'M,m': 'z',
 'N,n': 'a',
 'O,o': 'b',
 'P,p': 'c',
 'Q,q': '_',
 'R,r': '_',
 'S,s': '_',
 'T,t': '_',
 'U,u': 'h',
 'V,v': 'i',
 'W,w': 'j',
 'X,x': 'k',
 'Y,y': 'l',
 'Z,z': 'm'}

答案 1 :(得分:0)

{'D,d': 'q'}仍将单个键映射到值。将多个键映射到相同的值将类似于

from itertools import cycle
from string import ascii_letters

k = '_opqrst____yzabc____hijklm'
d = dict(zip(ascii_letters, cycle(k)))
然后

d

{'V': 'i', 'j': '_', 'E': 'r', 'B': 'o', 'S': '_', 'e': 'r', 'G': 't',
'l': 'y', 'O': 'b', 'k': '_', 'Y': 'l', 'o': 'b', 'R': '_', 't': '_', 'g': 
't', 'v': 'i', 'A': '_', 'C': 'p', 'u': 'h', 'J': '_', 'N': 'a', 'I': '_', 
'w': 'j', 'b': 'o', 'z': 'm', 'x': 'k', 'q': '_', 'a': '_', 'm': 'z', 'X': 
'k', 'i': '_', 'h': '_', 'p': 'c', 'W': 'j', 'r': '_', 'd': 'q', 'U': 'h', 
'P': 'c', 'F': 's', 'c': 'p', 'f': 's', 'y': 'l', 'D': 'q', 'Z': 'm', 's': 
'_', 'n': 'a', 'H': '_', 'Q': '_', 'M': 'z', 'L': 'y', 'T': '_', 'K': '_'}

如果您需要'D,d'键,则可以执行

from string import ascii_lowercase

d = {'{},{}'.format(a.upper(), a): b for a, b in zip(ascii_lowercase, k)}