如何将列表的列表放入 Python 中的字典?
How to put list of list into a dictionary in Python?
我有一个包含元组和字符串项的列表列表。像这样:
list_1 = [
[(1653865, "Mary Lee", "The best experience ever"), (2321343, "Jason Jacob", "Great"), "5432"],
[(1754322, "William Lee", "It was easier than I thought"), "1008432"],
[(424221, "Mark Zaby", "Newbie"), "12308"],
[(1754322, "William Lee", "Not good"), "987764"]
]
我想把它放在这样的字典中:
dic = {
1653865: ["Mary Lee", "The best experience ever", "5432"],
2321343: ["Jason Jacob", "Great", "5432"],
1754322: ["William Lee", "It was easier than I thought", "1008432", "987764"],
424221: ["Mark Zaby", "Newbie", "12308"]
}
元组中的第一项应该是键,其余的应该是值。但在示例中,对于 William Lee,他在两个列表中的最后一个元素不同,因此值被附加到字典中,因为键相同。
我试过这样做:
dic = dict()
for i in list_1:
if type(i) != tuple:
dic[i[0]] = None
for i in list_1:
value = i[-1]
for element in i:
if type(i) == tuple:
if i[0] in dic.keys():
dic.append(value)
但是代码不正确。
dic = {}
for item in list_1:
tuples = [i for i in item if isinstance(i, tuple)]
vals = [i for i in item if isinstance(i, str)]
for t in tuples:
key, *v = t
if key in dic:
dic[key] += vals
else:
dic[key] = [*v, *vals]
我有一个包含元组和字符串项的列表列表。像这样:
list_1 = [
[(1653865, "Mary Lee", "The best experience ever"), (2321343, "Jason Jacob", "Great"), "5432"],
[(1754322, "William Lee", "It was easier than I thought"), "1008432"],
[(424221, "Mark Zaby", "Newbie"), "12308"],
[(1754322, "William Lee", "Not good"), "987764"]
]
我想把它放在这样的字典中:
dic = {
1653865: ["Mary Lee", "The best experience ever", "5432"],
2321343: ["Jason Jacob", "Great", "5432"],
1754322: ["William Lee", "It was easier than I thought", "1008432", "987764"],
424221: ["Mark Zaby", "Newbie", "12308"]
}
元组中的第一项应该是键,其余的应该是值。但在示例中,对于 William Lee,他在两个列表中的最后一个元素不同,因此值被附加到字典中,因为键相同。
我试过这样做:
dic = dict()
for i in list_1:
if type(i) != tuple:
dic[i[0]] = None
for i in list_1:
value = i[-1]
for element in i:
if type(i) == tuple:
if i[0] in dic.keys():
dic.append(value)
但是代码不正确。
dic = {}
for item in list_1:
tuples = [i for i in item if isinstance(i, tuple)]
vals = [i for i in item if isinstance(i, str)]
for t in tuples:
key, *v = t
if key in dic:
dic[key] += vals
else:
dic[key] = [*v, *vals]