Y
Y
Yrets1692021-12-23 18:40:53
Python
Yrets169, 2021-12-23 18:40:53

How to combine two lists into a dictionary?

Good afternoon, there are two lists that need to be added to the dictionary

timestamp = [11111,22222,33333]
file_list = ['file1','file2','file3']
for file_time_created in file_list:
    files_dict = [ {'key':file_time_created, 'value': timestamp} ]

print(files_dict)


I get a response:
[{'key': 'file1', 'value': 11111}]
------------------------------------------------ -------------------------------------------------- ------------------------------
desired response:
[{'key': 'file1', 'value': 11111},{'key': 'file2', 'value': 22222},{'key': 'file3', 'value': 33333}]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Konstantin Nagibovich, 2021-12-23
@Yrets169

Declare a dictionary before the loop. In the loop, call the append method of your dictionary.

S
shurshur, 2021-12-23
@shurshur

timestamp = [11111,22222,33333]
file_list = ['file1','file2','file3']

files_dict = [{"key":k, "value":file_list[i]} for i,k in enumerate(timestamp)]

But in general, logically, it is more convenient to work with such data in the form of a dict, where the keys are timestamp values, and the values ​​are file names. It's even easier:
files_dict = dict(zip(timestamp, file_list))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question