Python - Modifying lists within a list - python

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.

Related

Rename duplicates in list of dictionaries by appending progressive numbers at end

Given a list of dictionaries like this
a_list = [{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer','roll_no':18}, {'name':'kristina','roll_no':33}]
How could this be renamed to
a_list = [{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer 1','roll_no':18}, {'name':'kristina 1','roll_no':33}]
You want to construct a new list of dictionaries, but whenever a new dictionary is added that has a 'name' value that was already present, you want to use the next available option.
There's different approaches but one would be:
loop over all the dictionaries in a_list and add them to a new list
before adding them, check some register of used names to see if their name is in there, if not, just add it; if so, get and increase the number associated with it and update the dictionary
So, in code:
a_list = [
{'name':'jennifer','roll_no':22}, {'name':'kristina','roll_no':26},
{'name':'jennifer','roll_no':18}, {'name':'kristina','roll_no':33}
]
names = {}
result = []
for d in a_list:
if (name := d['name']) not in names:
names[name] = 0
else:
names[name] += 1
d['name'] = f'{name} {names[name]}'
result.append(d)
print(result)
Result:
[{'name': 'jennifer', 'roll_no': 22}, {'name': 'kristina', 'roll_no': 26}, {'name': 'jennifer 1', 'roll_no': 18}, {'name': 'kristina 1', 'roll_no': 33}]

Extract part of a dictionary within a list by string condition in python

I have a list with dictionary contained within it in the format:
mydataset =
[{'thing1': 'pink',
'thing2': 'apple',
'thing3': 'car',
'data': [{'firstname': 'jenny',
'lastname': 'jones',
}]},
{'thing1': 'blue',
'thing2': 'banana',
'thing3': 'bicycle',
'data': [{'firstname': 'david',
'lastname': 'walls',
}]}]
I want to be able to extract all the items called firstname within 'data', i.e. 'jenny' and 'david'.
I've tried an approach of myextract = [x in x if mydataset['data']], but of course it fails because I think I'm looking for a value with that. My mental model of the data structure isn't right at the moment.
Try the following:
res = [i['data'][0]['firstname'] for i in mydataset]
output:
['jenny', 'david']
side note: please put banana and apple inside single quotes.
Use the following list comprehension:
res = [di["firstname"]for d in mydataset for di in d["data"] if "firstname" in di]
print(res)
Output
['jenny', 'david']
The above list comprehension is equivalent to the following for-loop:
res = []
for d in mydataset:
for di in d["data"]:
if "firstname" in di:
res.append(di["firstname"])
print(res)
Note that both solutions above will work for more than one element in the sub-dictionary d["data"] and even if the "firstname" key is not present.
For the sake of reusability you could also define a function that will let you access individual values in the dataset and use it for this particular example:
def nested_getitem(path, dic):
from operator import getitem
from functools import reduce
return reduce(getitem, path, dic)
res = [nested_getitem(["data", 0, "firstname"], d) for d in mydataset]
print(res)
Output
['jenny', 'david']

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

how to convert list containing ' : ' to dictionary in python

I am new to here and asking a question relating to python.
I have a list of city's name, population and area, for example:
city:NewYork population:30 area:1000
city:LosAngles population:3 area:500
.....
but the data is in a list, e.g.
list[0] = 'city:NewYork population:30 area:1000'
list[1] = 'city:LosAngles population:3 area:500'
I would like to convert this list to dictionary list,
the result like to be:
result[0]["city"] =NewYork
result[0]["population"] = 30
I tried many methods, but dont know how to solve it.
Can anyone help me?
thanks in advance!
Split on spaces, then on colons:
result = [dict(item.split(':') for item in value.split()) for value in inputlist]
where inputlist is the original list of strings.
Demo:
>>> inputlist = '''\
... city:NewYork population:30 area:1000
... city:LosAngles population:3 area:500
... '''.splitlines()
>>> [dict(item.split(':') for item in value.split()) for value in inputlist]
[{'city': 'NewYork', 'area': '1000', 'population': '30'}, {'city': 'LosAngles', 'area': '500', 'population': '3'}]

How to check if list item is in dictionary. If so, print the data associated with it

I have a list of names called names. I also have 2 dictionaries that contain a list of nested dictionaries that both have the key names and other data associated with the name. What I want to do is check that the name from the list is in one of the 2 dictionaries, if so, print the data associated only with that name. I can't find any of this stuff in the python docs
names = ['barry','john','george','sarah','lisa','james']
dict1 = {'results':[{'name':'barry','gpa':'2.9','major':'biology'},
{'name':'sarah','gpa':'3.2','major':'economics'},
{'name':'george','gpa':'2.5','major':'english'}]}
dict2 = {'staff':[{'name':'john','position':'Lecturer','department':'economics'},
{'name':'lisa','position':'researcher','department':'physics'},
{'name':'james','position':'tutor','department':'english'}]}
for x in names:
if x in dict1:
print gpa associated with the name
elif x in dict2:
print position associated with the name
The structure you're using for the two dicts isn't very optimal - each contains only a single element, which is a list of the relevant data for each person. If you can restructure those with a separate element per person using the name as a key, this becomes a trivial problem.
dict1 = {'barry': {'gpa':'2.9','major':'biology'},
'sarah': {'gpa':'3.2','major':'economics'},
'george': {'gpa':'2.5','major':'english'}}
dict2 = {'john': {'position':'Lecturer','department':'economics'},
'lisa': {'position':'researcher','department':'physics'},
'james': {'position':'tutor','department':'english'}}
Since it appears you can't get the data in this format, you'll have to convert it:
dict_results = dict((d['name'], d) for d in dict1[results])
if name in dict_results:
print dict_results[name]['gpa']
for _name in names:
if _name in [person['name'] for person in dict1['results']]: pass
elif _name in [person['name'] for person in dict2['staff']]:pass
something like that at least
This should get you an idea:
for name in names:
print name, ":"
print "\t", [x for x in dict2["staff"] if x["name"] == name]
print "\t", [x for x in dict1["results"] if x["name"] == name]
prints
barry :
[]
[{'major': 'biology', 'name': 'barry', 'gpa': '2.9'}]
john :
[{'department': 'economics', 'position': 'Lecturer', 'name': 'john'}]
[]
george :
[]
[{'major': 'english', 'name': 'george', 'gpa': '2.5'}]
sarah :
[]
[{'major': 'economics', 'name': 'sarah', 'gpa': '3.2'}]
lisa :
[{'department': 'physics', 'position': 'researcher', 'name': 'lisa'}]
[]
james :
[{'department': 'english', 'position': 'tutor', 'name': 'james'}]
[]
If you get this data from a database, you should probably rather work on the SQL frontier of the problem. A database is made for operations like that.
names = ['barry','john','george','sarah','lisa','james']
dict1 = {'results':[{'name':'barry','gpa':'2.9','major':'biology'},
{'name':'sarah','gpa':'3.2','major':'economics'},
{'name':'george','gpa':'2.5','major':'english'}]}
dict2 = {'staff':[{'name':'john','position':'Lecturer','department':'economics'},
{'name':'lisa','position':'researcher','department':'physics'},
{'name':'james','position':'tutor','department':'english'}]}
import itertools
for x in itertools.chain(dict1['results'], dict2['staff']):
for n in names:
if n in x.values():
print x
or the 2nd part could be:
ns = set(names)
for x in itertools.chain(dict1['results'], dict2['staff']):
if x['name'] in ns:
print x

Categories

Resources