python列表根据指定元素生成字典


列表的值是这样
mylist = [['3','ssss','123123453453234'],['4','ssss','3453464567345456'],['5','ssss','5687345324123123234'],['7','bbbb','96893543453463123234'],['8','bbbb','sdfsdfsdfsf'],['9','cccc','dfgdfg3242']]

要生成这样的字典
{'ssss':[{'3':'123123453453234'},{'4':'3453464567345456'},{'5':'5687345324123123234'},{'7':'96893543453463123234'}],'bbbb':[...],'cccc':[...]}
或者
{'ssss':[['3':'123123453453234'],['4':'3453464567345456'],['5':'5687345324123123234'],['7':'96893543453463123234']],'bbbb':[...],'cccc':[...]}

头都大了。。有没有现成的库做这个工作的?

字典 python

luck超人 9 years, 9 months ago

 mylist = [['3', 'ssss', '123123453453234'],
          ['4', 'ssss', '3453464567345456'],
          ['5', 'ssss', '5687345324123123234'],
          ['7', 'bbbb', '96893543453463123234'],
          ['8', 'bbbb', 'sdfsdfsdfsf'],
          ['9', 'cccc', 'dfgdfg3242']]
result = {}
for item in mylist:
    sub_key, key, value = item
    if not key in result:
        result[key] = []
    result[key].append({sub_key: value})
print result
# {'ssss': [{'3': '123123453453234'}, {'4': '3453464567345456'}, {'5': '5687345324123123234'}], 'cccc': [{'9': 'dfgdfg3242'}], 'bbbb': [{'7': '96893543453463123234'}, {'8': 'sdfsdfsdfsf'}]}
result1 = {}
for item in mylist:
    value1, key, value2 = item
    if not key in result1:
        result1[key] = []
    result1[key].append([value1, value2])
#{'ssss': [['3', '123123453453234'], ['4', '3453464567345456'], ['5', '5687345324123123234']], 'cccc': [['9', 'dfgdfg3242']], 'bbbb': [['7', '96893543453463123234'], ['8', 'sdfsdfsdfsf']]}
print result1

我勒个来的 answered 9 years, 9 months ago

Your Answer