Skip to content
Advertisement

Appending two lists with multiple dicts Python

I have five dictionaries dic1, dict2, dict3, dict4, dict5. I’m trying to append dict-keys to two lists list1, list2.

dict1 = {"brand": "Ford",
         "model": "Mustang",
         "year": 1964}

dict2 = {"brand": "Acura",
         "model": "Honda",
         "year": 1984}

dict3 = {"brand": "BMW",
         "model": "BMW",
         "year": 1974}

dict4 = {"brand": "Bentley",
         "model": "Volkswagen",
         "year": 1976}

dict5 = {"brand": "Cadillac",
         "model": "GM",
         "year": 1983}

Output

list1 = ['Ford', 'Mustang', 1964, 'Acura', 'Honda', 1984, 'BMW', 'BMW', 1974, 'Bentley', 'Volkswagen', 1976]
list2 = ['Ford', 'Mustang', 1964, 'Acura', 'Honda', 1984, 'BMW', 'BMW', 1974, 'Cadillac', 'GM', 1983]

The first three dictionaries are to be appended for both the lists and fourth dictionary dict4 to the list1 and fifth dict5 to the list2.

So far I did in this approach,

def appendListsFromDict():
    #create Empty List
    list1, list2 = [], []

    #Create blank lists and append lists from each of the dictionaries
    #Appending for list1
    for key in dict1:
        list1.append(dict1[key])

    for key in dict2:
        list1.append(dict2[key])

    for key in dict3:
        list1.append(dict3[key])

    # dict4
    for key in dict4:
        list1.append(dict4[key])   



    #Appending for list2
    for key in dict1:
        list2.append(dict1[key])

    for key in dict2:
        list2.append(dict2[key])

    for key in dict3:
        list2.append(dict3[key])

    # dict5
    for key in dict5:
        list2.append(dict5[key])   

    return list1, list2

I’m looking for an efficient and better approach to do this. Any suggestions or references would be highly appreciated.

Advertisement

Answer

You can use list.extend for the task

dicts = [dict1, dict2, dict3]

list1, list2 = [], []
for d in dicts:
    list1.extend(d.values())
    list2.extend(d.values())

list1.extend(dict4.values())
list2.extend(dict5.values())

print(list1)
print(list2)

Prints:

['Ford', 'Mustang', 1964, 'Acura', 'Honda', 1984, 'BMW', 'BMW', 1974, 'Bentley', 'Volkswagen', 1976]
['Ford', 'Mustang', 1964, 'Acura', 'Honda', 1984, 'BMW', 'BMW', 1974, 'Cadillac', 'GM', 1983]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement