new_user
new_user

Reputation: 25

How to put list of list into a dictionary in Python?

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.

Upvotes: 1

Views: 456

Answers (1)

user3064538
user3064538

Reputation:

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]

Upvotes: 2

Related Questions