简体   繁体   English

如果字典的值是一个列表,有没有办法更新字典中键的值?

[英]Is there a way to update the value of a key in a dictionary, if the value of the dictionary is a list?

I have four lists of special character strings eg '™'.我有四个特殊字符串列表,例如“™”。 I am storing them in a dictionary as the value to the keys 1 through 4.我将它们作为键 1 到 4 的值存储在字典中。

I am trying to loop through all items in each of the dictionary's lists and then update each value to its utf-8 encoded equivalent.我试图遍历每个字典列表中的所有项目,然后将每个值更新为其 utf-8 编码的等价物。 Here's what I have so far:这是我到目前为止所拥有的:

li1 = ['€','‚','ƒ','„','…','†','ˆ','‰']
li2 = ['Š','‹','Œ','Ž']
li3 = ['‘','’','“','”','•','–','—','˜','™']
li4 = ['š','›','œ','ž','Ÿ']

uni_dic = {
    '1':li1,
    '2':li2,
    '3':li3,
    '4':li4
}

for key in uni_dic:
    for val in uni_dic[key]:
        uni_dic.update({key,val.encode('utf-8')})

This returns a 'ValueError: dictionary update sequence element #0 has length 1;这将返回一个 'ValueError:字典更新序列元素 #0 的长度为 1; 2 is required' 2是必需的'

Take out the last three lines and write:把最后三行拿出来写:

for key, values in uni_dic.items():
    uni_dic[key] = [string.encode('utf-8') for string in values]

or in one line:或一行:

uni_dic = {key: [string.encode('utf-8') for string in uni_dic[key]] for key in uni_dic}

uni_dic} uni_dic}

In this case, you can create another list like below:在这种情况下,您可以创建另一个列表,如下所示:

for key in uni_dic:
    uni_dic[key] = [val.encode('utf-8') for val in uni_dic[key]]

If you want to do it in-place:如果您想就地进行:

for key in uni_dic:
    for idx, val in enumerate(uni_dic[key]):
        uni_dic[key][idx] = val.encode('utf-8')

The syntax error is that you're specifying your update dict as {key,val.encode('utf-8')} (which is actually a set ) instead of {key: val.encode('utf-8')} .语法错误是您将更新字典指定为{key,val.encode('utf-8')} (实际上是一个set )而不是{key: val.encode('utf-8')} . However, it's a bit silly to use update to update a single key anyway, and they way you're looping through the list, you'll just be overwriting the list repeatedly with each element in turn (ultimately ending up with the last item).但是,无论如何使用update来更新单个键有点愚蠢,而且它们是循环列表的方式,您只需依次用每个元素重复覆盖列表(最终以最后一项结束) .

Instead, build a new list out of the encoded values, and assign the entire list to uni_dic[key] :相反,从编码值中构建一个新列表,并将整个列表分配给uni_dic[key]

for key in uni_dic:
    encoded_vals = []
    for val in uni_dic[key]:
        encoded_vals.append(val.encode('utf-8'))
    uni_dic[key] = encoded_vals 

Using a list comprehension to build encoded_vals gets you the much more concise:使用列表理解来构建encoded_vals可以使您更加简洁:

for key in uni_dic:
    uni_dic[key] = [val.encode('utf-8') for val in uni_dic[key]]

And using a dictionary comprehension with dict.items() makes it even simpler:并使用dict.items()的字典理解使它更简单:

uni_dic = {k: [val.encode('utf-8') for val in v] for k, v in uni_dic.items()}

A one-line solution to your question is:您的问题的单线解决方案是:

uni_dic = {key:[val.encode('utf-8') for val in charList] for key, charList in uni_dic.items()}

To get the same result with a minimal modification to the code in your question, you could do this:要通过对问题中的代码进行最少的修改来获得相同的结果,您可以这样做:

li1 = ['€','‚','ƒ','„','…','†','ˆ','‰']
li2 = ['Š','‹','Œ','Ž']
li3 = ['‘','’','“','”','•','–','—','˜','™']
li4 = ['š','›','œ','ž','Ÿ']

uni_dic = {
    '1':li1,
    '2':li2,
    '3':li3,
    '4':li4
}

for key in uni_dic:
    charList = uni_dic[key]
    for i, val in enumerate(charList):
        charList[i] = val.encode('utf-8')
[print(charList) for charList in uni_dic.values()]

Output: Output:

[b'\xe2\x82\xac', b'\xe2\x80\x9a', b'\xc6\x92', b'\xe2\x80\x9e', b'\xe2\x80\xa6', b'\xe2\x80\xa0', b'\xcb\x86', b'\xe2\x80\xb0']
[b'\xc5\xa0', b'\xe2\x80\xb9', b'\xc5\x92', b'\xc5\xbd']
[b'\xe2\x80\x98', b'\xe2\x80\x99', b'\xe2\x80\x9c', b'\xe2\x80\x9d', b'\xe2\x80\xa2', b'\xe2\x80\x93', b'\xe2\x80\x94', b'\xcb\x9c', b'\xe2\x84\xa2']
[b'\xc5\xa1', b'\xe2\x80\xba', b'\xc5\x93', b'\xc5\xbe', b'\xc5\xb8']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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