如何在循环内的字典中的键中添加值?

Mpi*_*ris 5 python dictionary list

我有以下列表:

x=['a','3','4','b','1','2','c','4','5']
Run Code Online (Sandbox Code Playgroud)

我怎样才能制作以下字典:

b = {'a':[3,4],'b':[1,2],'c':[4,5]}
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

Category = defaultdict(int)
for i in a:
    if Varius.is_number(i)==False:
        Category[i]=[]
        keys.append(i)
    else:
        Category[keys(i)] = i
Run Code Online (Sandbox Code Playgroud)

密钥是在我有问题插入值后创建的.(is_number是一个检查列表值是数字还是字符串的函数).第一天离开MATLAB.第一天在Python中..

Pet*_*erE 4

defaultdict这里是一个实际使用了正常提供的功能的示例dict

from collections import defaultdict

x=['a','3','4','b','1','2','c','4','5']

key='<unknown>' # needed if the first value of x is a number
category = defaultdict(list)  # defaultdict with list
for i in x:
    if i.isalpha():
        key = i;
    else:
        category[key].append(i) # no need to initialize with an empty list

print category
Run Code Online (Sandbox Code Playgroud)

另外:您应该为类实例使用小写名称。大写名称通常是为类保留的。阅读pep8获取风格指南。