无法将列表列表转换为python中的字典

2024-04-19 22:16:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份名单:

[['Grade', 'V A'], ['Attendance', '16/26'], ['Session timings', '8:00 am - 8:40 am'], ['Grade', 'VII A'], ['Attendance', '24/31'], ['Session timings', '8:50 am - 9:30 am'], ['Grade', 'IX A'], ['Attendance', '20/26'], ['Session timings', '9:40 am - 10:20 am'], ['Grade', 'IX B'], ['Attendance', '21/25'], ['Session timings', '10:50 am - 11:30 am']]

并希望将其转换为如下所示的字典:-

{{"Grade":"V A"}, {"Attendance": "16/26"} ... }

我尝试使用zip方法:-

keys = []
values = []

for i in range(0, 12):
    string = str(message_list[i]).replace(',',';').replace('[','').replace(']','').replace("'","").split(";")
    keys.append(string[0])
    values.append(string[1])

new_dict = dict(zip(keys, values))
print(new_dict)

但它只打印:

{'Grade': ' IX B', 'Attendance': ' 21/25', 'Session timings': ' 10:50 am - 11:30 am'}

它只打印IX B级,不打印其他3级。请帮我查一下密码

但是当我使用new_dict = list(zip(keys, values))时,它将整个打印为元组列表:

[('Grade', ' V A'), ('Attendance', ' 16/26'), ('Session timings', ' 8:00 am - 8:40 am'), ('Grade', ' VII A'), ('Attendance', ' 24/31'), ('Session timings', ' 8:50 am - 9:30 am'), ('Grade', ' IX A'), ('Attendance', ' 20/26'), ('Session timings', ' 9:40 am - 10:20 am'), ('Grade', ' IX B'), ('Attendance', ' 21/25'), ('Session timings', ' 10:50 am - 11:30 am')]

那为什么不打印完整的字典呢?请帮我查一下密码

谢谢大家!


Tags: newstring字典sessionkeyszipamdict
2条回答

原因是您正在覆盖已存在的密钥,因此只能在dict中看到list的最后一个条目。另一种方法是使用嵌套的dict,如下所示:

{
    'Grade-V A': {
        'Attendance': '16/26',
        'Session timings': '8:00 am - 8:40 am'
    },
    'Grade-VII A': {
        'Attendance': '24/31',
        'Session timings': '8:50 am - 9:30 am'
    },
    'Grade-IX A': {
        'Attendance': '20/26',
        'Session timings': '9:40 am - 10:20 am'
    },
    'Grade-IX B': {
        'Attendance': '21/25',
        'Session timings': '10:50 am - 11:30 am'
    }
}

使用以下代码:

data = [['Grade', 'V A'], ['Attendance', '16/26'], ['Session timings', '8:00 am - 8:40 am'], ['Grade', 'VII A'], ['Attendance', '24/31'], ['Session timings', '8:50 am - 9:30 am'], ['Grade', 'IX A'], ['Attendance', '20/26'], ['Session timings', '9:40 am - 10:20 am'], ['Grade', 'IX B'], ['Attendance', '21/25'], ['Session timings', '10:50 am - 11:30 am']]

output = {}
for item in data:
    if item[0] == 'Grade':
        grade = item[0]+'-'+item[1]
        output[grade] = {}
    else:
        output[grade][item[0]] = item[1]
        
print (output)

同一个键(例如,“Grade”)在字典中不能重复多次。。。密钥必须是唯一的

您可以这样做:

from collections import defaultdict

d = defaultdict(list)
for k, v in lst:
    d[k].append(v)
d = dict(d)

结果是:

{'Grade': ['V A', 'VII A', 'IX A', 'IX B'],
 'Attendance': ['16/26', '24/31', '20/26', '21/25'],
 'Session timings': ['8:00 am - 8:40 am', '8:50 am - 9:30 am', '9:40 am - 10:20 am', '10:50 am - 11:30 am']}

相关问题 更多 >