Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading