I have a list of list containing tuples and string items. Like this:
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"]
]
I want to put it in a dictionary like this:
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"]
}
The first item in the tuple should be the key and the rest should be the values. But in the example, in case of William Lee, he has a different last element in the two lists, so the value is appended in the dictionary because of the key is the same.
I have tried doing it this way:
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)
but the code is not correct.
CodePudding user response:
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]
CodePudding user response:
If the last element of each sub-list is the only value to be appended and the rest are tuples, we can skip building tuples
and vals
as in Boris Verkhovskiy's answer and build dic
in a nested loop.
dic = {}
for sub_list in list_1:
# iterate until the penultimate element in each sub-list (the last element is the value)
for key, *v in sub_list[:-1]:
# if the key is already in dic, append only the last element to the value
if key in dic:
dic[key].append(sub_list[-1])
# if not, create a new key-value pair
else:
dic[key] = v [sub_list[-1]]
res
{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']}