I've got lists:
host = ['host1', 'host2', 'host3']
user = ['first_user', 'second_user', '-']
time = ['01/01', '02/02', '03/03']
I want to have list of dictionaries where each dict looks like below:
{'host': 'host1',
'user': 'firsts_user',
'time': '01/01'}
How would you do that?
Frankly, the question is not clear enough but I implement this from what I understand;
>>> host = ['host1', 'host2', 'host3']
>>> user = ['first_user', 'second_user', '-']
>>> time = ['01/01', '02/02', '03/03']
>>>
>>> d = []
>>> for i in range(len(host) - 1):
... d.append({
... host[i]: host[i + 1],
... user[i]: user[i + 1],
... time[i]: time[i + 1]
... })
...
>>> print(d)
[{'host1': 'host2', 'first_user': 'second_user', '01/01': '02/02'}, {'host2': 'host3', 'second_user': '-', '02/02': '03/03'}]
Very slight modification of the Cenk Bircanoglu answer where all dictionary keys are fixed rather than having them referring to the follow-up element. I assume that was asked.
d = []
for count, el in enumerate(host):
d.append({
'host': el,
'user': user[count] if len(user) >= count+1 else None,
'time': time[count] if len(time) >= count+1 else None
})
print(d)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.