Home > database >  How to insert items in a dictionary against their respective keys
How to insert items in a dictionary against their respective keys

Time:02-23

Have a usecase where I want to add the list items to a dictionary and the list items will be used as a key value pair in the dictionary. For example

Input list and dictionary

list_Items = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]

dict = {"tire1": {}, "tire2": {}}

Expected output of print(dict)

{"tire1": {"source": ["test1", "test2", "test3"]}, "tire2": {"source": ["test4", "test5", "test6"]}}

Thanks

CodePudding user response:

You definitely don't want a variable called dict as that would override the built-in of the same name. Otherwise it's simple:

list_items = [["test1", "test2", "test3"], ["test4", "test5", "test6"]]

result = dict()

for i, item in enumerate(list_items, 1):
    result[f'tire{i}'] = {'source': item}

print(result)

Output:

{'tire1': {'source': ['test1', 'test2', 'test3']}, 'tire2': {'source': ['test4', 'test5', 'test6']}}

CodePudding user response:

You can do something like:

d = {}
for i in range(len(list_Items)):
    d["tire{}".format(i 1)] = {"source": list_Items[i]}

Note that dict itself is a reserved keyword, hence I've used d instead.

  • Related