How can I map 3 lists to dictionary keys - python

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',
}]

I guess you want something like this
given_task = [{'name': i, 'date_due': j} for i, j in zip(task_names, date_due)]

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'}]

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]})

Related

Adding items from list to the dictionaries in another list [duplicate]

This question already has answers here:
How do I iterate through two lists in parallel?
(8 answers)
Closed 9 months ago.
I'm trying to add items from list to the dictionaries in another list.
info = [{'id' : 1, 'tag' : 'Football'}, {'id' : 2, 'tag' : 'MMA'}]
dates = ['May 1st', 'April 23rd']
for item in dates:
for dic in info:
dic['date'] = item
This is what I want to get:
[{'id': 1, 'tag': 'Football', 'date': 'May 1st'},
{'id': 2, 'tag': 'MMA', 'date': 'April 23rd'}]
But instead of it I get this:
[{'id': 1, 'tag': 'Football', 'date': 'April 23rd'},
{'id': 2, 'tag': 'MMA', 'date': 'April 23rd'}]
Correct me please.
If you nest the for cycles then only the last iteration of the first for matters.
The correct way to do it is cycling in parallel over the two list, using the function zip.
info = [{'id' : 1, 'tag' : 'Football'}, {'id' : 2, 'tag' : 'MMA'}]
dates = ['May 1st', 'April 23rd']
for item,dic in zip(dates,info):
dic['date'] = item
You can add a new key-value pair to each dict in the list as follows:
for i in range(len(info)):
info[i]['date'] = dates[i]

Getting value in nested dictionary and list

Hello I'm trying to gain the number values from this kind of format:
{'Hello' : {'Values': [{'Number': 2, 'Name': 'John'},{'Number': 5, 'Name' : 'Bob'}, {'Number':7, 'Name' : 'Fred'}]}}
How will this be possible in python? I'm trying to get this output
[2,5,7]
and
['John', 'Bob', 'Fred']
Thank you very much.
So far I've tried to see how many times the for loop would run so I ran
for i in dictionary_name['Hello']['Values']
dict = {'Hello' : {'Values': [{'Number': 2, 'Name': 'John'},{'Number': 5, 'Name' : 'Bob'}, {'Number':7, 'Name' : 'Fred'}]}}
numbers = []
names = []
for val in dict['Hello']['Values']:
numbers.append(val['Number'])
names.append(val['Name'])
You can use list comprehension :
my_dict = {'Hello' : {'Values': [{'Number': 2, 'Name': 'John'},{'Number': 5, 'Name' : 'Bob'}, {'Number':7, 'Name' : 'Fred'}]}}
numbers = [key['Number'] for key in my_dict['Hello']['Values']]
names = [key['Name'] for key in my_dict['Hello']['Values']]

Python - Modifying lists within a list

Consider myself a beginner with Python. I'm trying to do something I've not quite done before and am completely stumping myself.
Hoping someone can give me a clue as which path to take on this.
I have a number of lists within a larger list.
I would like to iterate through the large list and modify data in each sub-list. There are a number of common variables within each list, but not all lists will be the same.
Example:
LIST = [
['Name: Dave', 'Age 28', 'Dogs', 'Football',],
['Name: Tony', 'Age 22', 'Beer', 'Star Wars', 'Hotdogs']
]
The end goal is to have 1 large list with each sublist converted to a dictionary.
Goal:
LIST = [
{'Dave' : { 'Age' : '28' } {'Likes' : ['Dogs', 'Football']}},
{'Tony' : { 'Age' : '22' } {'Likes' : ['Beer', 'Star Wars', 'Hotdogs']}}
]
The conversion to dictionary I will worry about later. But I am struggling to get my head around working with each sub-list in a loop.
Any ideas would be highly appreciated.
Thanks!
list2 = []
for el in list1:
list2.append( compute(el))
where compute is a method that will turn your list into the dictionary you want
result = {}
temp = {}
for x in LIST:
key = x[0][6:]
key_1 = x[1][:3]
value_1 = x[1][3:]
key_2 = 'Likes'
value_2 = x[2:]
temp[key_1] = value_1
temp[key_2] = value_2
result[key] = temp
temp = {}
Try this
but as you know dictionary has no sequence , no guarantee for age to be second in dictionary
Here's an answer to get your dictionary in both the ways mentioned by Tom Ellis.
LIST = [
['Name: Dave', 'Age 28', 'Dogs', 'Football', ],
['Name: Tony', 'Age 22', 'Beer', 'Star Wars', 'Hotdogs']
]
l = list()
for li in LIST:
d = dict()
likes_list = []
for i in li:
if "name" in i.lower():
d.update(dict([i.replace(' ', '').split(":")])) #removing the whitespace for formatting.
elif "age" in i.lower():
d.update(dict([i.split()]))
else:
likes_list.append(i)
d["likes"] = likes_list
l.append(d)
print l
Which results in:
>>> [{'Age': '28', 'Name': 'Dave', 'likes': ['Dogs', 'Football']}, {'Age': '22', 'Name': 'Tony', 'likes': ['Beer', 'Star Wars', 'Hotdogs']}]
If you really want the dictionary in the format you stated first, you could continue with the program like this:
l2 = []
for element in l:
nd = {}
name = element.pop("Name").strip()
nd[name] = element
# print nd
l2.append(nd)
print l2
Which results in the way you stated:
>>> [{'Dave': {'Age': '28', 'likes': ['Dogs', 'Football']}}, {'Tony': {'Age': '22', 'likes': ['Beer', 'Star Wars', 'Hotdogs']}}]
Axnyff's answer is pretty much what you want
ShadowRanger's comment on Axnyff's answer is definitely what you want. List comprehensions are really cool!
Simply iterating over the list with a for loop lets you work on each sub-list and do whatever you want to it.
It looks like you don't really want to modify the lists in place, rather you want to process each list into a dictionary (and extracting that process into a separate function is very good for readability), and put those new dictionaries into a new list.
EDIT:
Also, as correctly mentioned in a down-voted answer, your dictionaries should probably be in the form:
{'Name': 'Dave', 'Age': 28, 'Likes': ['Dogs', 'Football']}
Unless you actually want to use the dictionary to find their information by their name, in which case this is the correct syntax:
{'Dave' : { 'Age' : 28, 'Likes' : ['Dogs', 'Football']}}
LIST=[{'Name': 'Dave', 'Age': 28, 'likes':['Dogs', 'Football']},{'Name': 'Tony', 'Age': 22, 'likes':['Beer', 'Star Wars', 'Hotdogs']}]
You Do like This, Thank You.

Creating 2D dictionary in Python

I have a list of details from an output for "set1" which are like "name", "place", "animal", "thing"
and a "set2" with the same details.
I want to create a dictionary with dict_names[setx]['name']... etc On these lines.
Is that the best way to do it? If not how do I do it?
I am not sure how 2D works in dictionary.. Any pointers?
It would have the following syntax
dict_names = {
'd1': {
'name': 'bob',
'place': 'lawn',
'animal': 'man'
},
'd2': {
'name': 'spot',
'place': 'bed',
'animal': 'dog'
}
}
You can then look things up like
>>> dict_names['d1']['name']
'bob'
To assign a new inner dict
dict_names['d1'] = {'name': 'bob', 'place': 'lawn', 'animal': 'man'}
To assign a specific value to an inner dict
dict_names['d1']['name'] = 'fred'
Something like this would work:
set1 = {
'name': 'Michael',
'place': 'London',
...
}
# same for set2
d = dict()
d['set1'] = set1
d['set2'] = set2
Then you can do:
d['set1']['name']
etc. It is better to think about it as a nested structure (instead of a 2D matrix):
{
'set1': {
'name': 'Michael',
'place': 'London',
...
}
'set2': {
'name': 'Michael',
'place': 'London',
...
}
}
Take a look here for an easy way to visualize nested dictionaries.
Something like this should work.
dictionary = dict()
dictionary[1] = dict()
dictionary[1][1] = 3
print(dictionary[1][1])
You can extend it to higher dimensions as well.
If I understand your question properly, what you need here is a nested dictionary.You can use the addict module to create nested dictionaries quite easily.
https://github.com/mewwts/addict
if the items in each set is ordered, you could use the below approach
body = Dict()
setx = ['person1','berlin','cat']
sety = ['person2','jena','dog']
setz = ['person3','leipzig','tiger']
for set_,s in zip([setx,sety,setz],['x','y','z']):
for item,item_identifier in zip(set_,['name','city','animmal']):
body[f'set{s}'][f'{item_identifier}'] = item
now you can easily access the items as follows.
print(body['setx']['name'])
Simple one-liner for a nested 2D dictionary ( dict_names = {} ) :
dict_names.setdefault('KeyX',{})['KeyY']='Value'

Iterate through list of dictionary and create new list of dictionary

My data is as follows.
[
{
"id" : "123",
"type" : "process",
"entity" : "abc"
},
{
"id" : "456",
"type" : "product",
"entity" : "ab"
}
]
I am looping though it as follows to get id and entity
for test in serializer.data:
qaResultUnique['id'] = test['id']
qaResultUnique['entity'] = test['entity']
uniqueList.append(qaResultUnique)
but getting wrong output as only getting 2nd dictionary both times .
[
{
"id" : "456",
"entity" : "ab"
},
{
"id" : "456",
"entity" : "ab"
}
]
What I am doing wrong , please help.
You are reusing the qaResultUnique dictionary object. Create a new dictionary in the loop each time:
for test in serializer.data:
qaResultUnique = {}
qaResultUnique['id'] = test['id']
qaResultUnique['entity'] = test['entity']
uniqueList.append(qaResultUnique)
or more succinctly expressed:
uniqueList = [{'id': test['id'], 'entity': test['entity']} for test in serializer.data]
As #Martijn explained the actual problem, you can actually do this with dictionary comprehension like this
keys = {"type"}
print [{k:c_dict[k] for k in c_dict if k not in keys} for c_dict in data]
# [{'id': '123', 'entity': 'abc'}, {'id': '456', 'entity': 'ab'}]
You can use this method to skip any number of keys, without having to change the dictionary comprehension part. For example, if you have to skip both type and entity
keys = {"type", "entity"}
print [{k:c_dict[k] for k in c_dict if k not in keys} for c_dict in data]
# [{'id': '123'}, {'id': '456'}]
Just modify like this.
Before:
uniqueList.append(qaResultUnique)
After:
uniqueList.append(dict(qaResultUnique))
you can always do it like following
for test in serializer.data:
uniqueList.append({'id':test['id'],'entity':test['entity']})
or in list comprehension
uniqueList=[{'id':test['id'],'entity':test['entity']} for test in serializer.data]

Categories

Resources