Python:在字典中反转键和值,考虑字符串而不是字符
我必须在字典中反转键和值,但它不考虑整个字符串,而是逐个字符地考虑 我的代码如下:Python:在字典中反转键和值,考虑字符串而不是字符,python,dictionary,Python,Dictionary,我必须在字典中反转键和值,但它不考虑整个字符串,而是逐个字符地考虑 我的代码如下: locat= {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'} location = {} for e, char in locat.items(): location.setdefault(char, []).append(e) 因此,我: {'aa': [1, 1], 'ab': [2, 4, 2, 4], 'ba': [3]} 但我期待着这样的结果: {'aa'
locat= {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'}
location = {}
for e, char in locat.items():
location.setdefault(char, []).append(e)
因此,我:
{'aa': [1, 1], 'ab': [2, 4, 2, 4], 'ba': [3]}
但我期待着这样的结果:
{'aa': [1], 'ab': [2, 4], 'ba':[3]}
先谢谢你
关于,试试这个:
c={}
dict = {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'}
for e, char in dict.items():
c.setdefault(char, []).append(e)
print(c)
输出:
{'aa': [1], 'ab': [2, 4], 'ba': [3]}
defaultdict(<class 'list'>, {'aa': [1], 'ab': [2, 4], 'ba': [3]})
或
输出:
{'aa': [1], 'ab': [2, 4], 'ba': [3]}
defaultdict(<class 'list'>, {'aa': [1], 'ab': [2, 4], 'ba': [3]})
Python 2.x试试以下方法:
import __builtin__
print(__builtin__.dict(c))
顺便说一下,不要使用dict作为变量。您可以这样做:
location = {1: 'aa', 2: 'ab', 3: 'ba', 4: 'ab'}
location_new={}
for i,s in location.items():
if s in location_new:
location_new[s]+=[i]
else:
location_new[s]=[i]
print(location_new)
输出:
{'aa': [1], 'ab': [2, 4], 'ba': [3]}
剩余部分:
不要使用dict
或list
或任何其他类型作为变量,这将在以后导致错误。使用
我使用列表理解
[k代表dict中的k如果dict[k]
计算每个键的值请提供填充代码(位置2)不是粘贴的代码的一部分。不要将dict用作变量是dict
应该是locat
?如果是这样,您的代码是正确的,并且在Python 2和Python 3上都能正确工作。@Amy21:您发布的代码实际上是正确的。您是否有可能多次运行该单元格?dict位于索引中谢谢,我如何访问只使用字典而不使用defaultdict…添加一些关于代码的解释将有助于未来用户理解答案。
{v:[k for k in dict if dict[k] == v] for v in dict.itervalues()}