Ilko1810
Ilko1810

Reputation: 7

How can I map 3 lists to dictionary keys

Im trying to create a type of todo list application. The problem is this:

All the task names are stored in a list. All the due dates are stored in a different list. And so on. How can I combine these lists to get a dictionary like this.

task_names = ['test1', 'hw 1']
date_due = ['17 Dec', '16 Jan']

given_task = [{
    'name' : 'test1',
    'date_due' : '17 Dec', 
  }
, {
    'name' : 'hw1',
    'date_due' : '16 Jan', 
  }]

Upvotes: 0

Views: 65

Answers (3)

recursive_tree
recursive_tree

Reputation: 1

First of all: given_task is no valid python structure. I think you want a list filled with dictionaries like

    given_task = [{
        'name' : 'test1',
        'date_due' : '17 Dec', 
      }
    , {
        'name' : 'hw1',
        'date_due' : '16 Jan', 
      }]

As far as I understand, there are always the same amount of task names and taskdates. In this case you can iterate over all tasks and add them to a list.

    given_task = []
    for i in range(len(task_names)):
        given_task.append({'name':task_names[i],'date_due':dates_due[i]})

Upvotes: 0

Rakesh
Rakesh

Reputation: 82765

This is one approach using zip and dict in a list comprehension

Ex:

task_names = ['test1', 'hw 1']
date_due = ['17 Dec', '16 Jan']
keys = ['name', 'date_due']

print([dict(zip(keys, i)) for i in zip(task_names, date_due)])

Output:

[{'date_due': '17 Dec', 'name': 'test1'},
 {'date_due': '16 Jan', 'name': 'hw 1'}]

Upvotes: 0

Alexey
Alexey

Reputation: 178

I guess you want something like this

given_task = [{'name': i, 'date_due': j} for i, j in zip(task_names, date_due)]

Upvotes: 4

Related Questions