Beginner issue with random.choice - python

I want to create a list of students for each class, and then be able to randomly select a student.
import random
period1 = ['bern', 'brian', 'molly', 'pizza', 'dave', 'deena', 'tom', 'kelly']
period2 = ['bob', 'shane', 'marge', 'frank', 'Becky ', 'Delilah ', 'Teddy', 'Hudson']
random_student = input('Which class needs a volunteer?')
print(random.choice(random_student))

I think you will be better off creating a dictionary rather than using lists.
import random
period1 = ['bern', 'brian', 'molly', 'pizza', 'dave', 'deena', 'tom', 'kelly']
period2 = ['bob', 'shane', 'marge', 'frank', 'Becky ', 'Delilah ', 'Teddy', 'Hudson']
random_student = input('Which class needs a volunteer?')
d = {'period1': period1, 'period2': period2}
print(random.choice(d[random_student]))
input returns a string and not a variable. For example input will return 'period1' as a string while you want to call the variable period1 One way to get around this is to create a dictionary using a key and value pair. The key will be a string: 'period1' and the values will be a list of student names. Now you will be able to filter to the list you want with a string.

Related

How to replace values in nested dictionaries by new values in a list in python

I am iterating through a list of dictionaries. I need to update the values for one specific key in all the dictionaries and I have the new values stored in a list. The list of new values is ordered so that the 1st new value belongs to a key in the 1st dictionary, 2nd new value to a key in the 2nd dictionary, etc.
My data looks something like this:
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
And I want to transform the list of dictionaries using the list of new jobs according to my description into this:
dict_list = [{'person':'Tom', 'job':'lecturer'},
{'person':'John', 'job':'cook'},
{'person':'Mary', 'job':'driver'}]
As I have a very long list of dictionaries I would like to define a function that would do this automatically but I am struggling how to do it with for loops and zip(), any suggestions?
I tried the for loop below. I guess the following code could work if it was possible to index the dictionaries like this dictionary['job'][i] Unfortunately dictionaries don't work like this as far as I know.
def update_dic_list():
for dictionary in dict_list:
for i in range(len(new_jobs)):
dictionary['job'] = new_jobs[i]
print(dict_list)
The output the code above gave me was this:
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'teacher'}, {'person': 'Mary', 'job': 'manager'}]
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'manager'}]
[{'person': 'Tom', 'job': 'driver'}, {'person': 'John', 'job': 'driver'}, {'person': 'Mary', 'job': 'driver'}]
If your new_jobs list has the right job for each corresponding entry in the dict list, you could use zip:
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
for d, j in zip(dict_list, new_jobs):
d['job'] = j
print(dict_list)
prints
[{'person': 'Tom', 'job': 'lecturer'}, {'person': 'John', 'job': 'cook'}, {'person': 'Mary', 'job': 'driver'}]
With your loop, for each dictionary, you're going through the new jobs and updating that same dictionary over and over with each of the jobs until the last one. So by the end of it, they'll all be drivers. Because that's the last one.
You can do
dict_list = [{'person':'Tom', 'job':'student'},
{'person':'John', 'job':'teacher'},
{'person':'Mary', 'job':'manager'}]
new_jobs = ['lecturer', 'cook', 'driver']
def update_dic_list():
for job, _dict in zip(new_jobs, dict_list):
_dict['job'] = job
or
def update_dict_list():
for i, job in enumerate(new_jobs):
dict_list[i]['job'] = job
You only need to remove the inner loop because you are changing dictionary key job more than one time for each of item of outer loop:
def update_dic_list():
i = 0
for dictionary in dict_list:
dictionary['job'] = new_jobs[i]
i += 1
print(dict_list)
Or alternatively you could use enumerate:
def update_dic_list():
for i, dictionary in enumerate(dict_list):
dictionary['job'] = new_jobs[i]
print(dict_list)
Output:
[{'person': 'Tom', 'job': 'lecturer'}, {'person': 'John', 'job': 'cook'}, {'person': 'Mary', 'job': 'driver'}]

Add key and value of one list of dictionaries to another list of dictionaries

I have two python lists of dictionaries.
One is a keylist with multiple ids and date when updated.
Other list is about persons, in list of persons there is person_id which corresponds with p_id in the keylist. I want to add the fam_id from keylist to persons dictionary.
keylist = [{'p_id':'001','fam_id':'FAM98','update':'2021-07-29'},
{'p_id':'002','fam_id':'FAM1978','update':'2021-07-29'},
{'p_id':'003','fam_id':'FAM1978','update':'2021-07-29'}]
persons = [{'person_id':'001','dob':'01-20-1997','mom_id':'34','color':'brown'},
{'person_id':'002','dob':'12-05-2001','mom_id':'003', 'color':'black'},
{'person_id':'003','dob':'01-02-1977','mom_id':'320', 'color':'brown'}]
I would like to get:
persons = [{'person_id':'001','dob':'01-20-1997','mom_id':'34','color':'brown','fam_id':'FAM98'},
{'person_id':'002','dob':'12-05-2001','mom_id':'003','color':'black','fam_id':'FAM1978'},
{'person_id':'003','dob':'01-02-1977','mom_id':'320','color':'brown','fam_id':'FAM1978'}]
I don't know how to get this.
What I tried was this (but I don't know how to get lcreate from keylist):
lcreate = {'001': 'FAM98', '002': 'FAM1978', '003': 'FAM1978'}
for dic in persons: dic["fam_id"] = lcreate[dic["person_id"]]
How can I get one dict(lcreate) from list of dict (keylist)?
You can loop over both lists, and update persons dictionaries when those keys match.
keylist=[{'p_id':'001','fam_id':'FAM98','update':'2021-07-29'},{'p_id':'002','fam_id':'FAM1978','update':'2021-07-29'},{'p_id':'003','fam_id':'FAM1978','update':'2021-07-29'}]
persons=[{'person_id':'001','dob':'01-20-1997','mom_id':'34', 'color':'brown'},{'person_id':'002','dob':'12-05-2001','mom_id':'003', 'color':'black'},{'person_id':'003','dob':'01-02-1977','mom_id':'320', 'color':'brown'}]
for x in persons:
for y in keylist:
if x['person_id'] == y['p_id']:
x['fam_id'] = y['fam_id']
Result
>>> persons
[{'person_id': '001', 'dob': '01-20-1997', 'mom_id': '34', 'color': 'brown', 'fam_id': 'FAM98'},
{'person_id': '002', 'dob': '12-05-2001', 'mom_id': '003', 'color': 'black', 'fam_id': 'FAM1978'},
{'person_id': '003', 'dob': '01-02-1977', 'mom_id': '320', 'color': 'brown', 'fam_id': 'FAM1978'}]

Write Values to Empty List of Dictionaries

I have a list of names of unknown length. I want to write the names with their corresponding key (name to an empty list of dictionaries).
Input:
names = ['john', 'bill']
Output:
[{'name': 'john'}, {'name': 'bill'}]
Here it is:
names = ['john', 'bill']
dic = [{'name': name} for name in names]
print(dic)
#[{'name': 'john'}, {'name': 'bill'}]

Count frequency of words inside a list in a dictionary

I have a list of common keywords:
common_keywords = ['dog', 'person', 'cat']
And a list of dictionaries, containing keywords and sometimes the common_keywords listed above:
people = [{'name':'Bob', 'keywords': ['dog', 'dog', 'car', 'trampoline']},
{'name':'Kate', 'keywords': ['cat', 'jog', 'tree', 'flower']},
{'name':'Sasha', 'keywords': ['cooking', 'stove', 'person', 'cat']}]
I would like to count the frequency of the common_keywords for each person, so the desired output would look something like:
counts = [{'name': 'Bob', 'counts': [{'dog': 2}]},
{'name': 'Kate', 'counts': [{'cat': 1}]},
{'name': 'Sasha', 'counts': [{'person':1}, {'cat': 1}]]
I am able to use dict(Counter()) to count the keywords and filter them if they appear in the common_keywords but I am struggling with linking these counts back to the original name as shown in the desired output: counts.
Current code (I think I am slowly getting there):
freq_dict = {}
for p in people:
name = p['name']
for c in p['keywords']:
if c not in freq_dict:
freq_dict[name] = {c: 1}
else:
if c not in freq_dict[name]:
freq_dict[c] = 1
else:
freq_dict[c] +=1
You can use a list-comprehension along with collections.Counter which does exactly what you want with the nested list. -
from collections import Counter
[{'name':i.get('name'),
'keywords':[dict(Counter([j for j in i.get('keywords')
if j in common_keywords]))]} for i in people]
[{'name': 'Bob', 'keywords': [{'dog': 2}]},
{'name': 'Kate', 'keywords': [{'cat': 1}]},
{'name': 'Sasha', 'keywords': [{'person': 1, 'cat': 1}]}]
First, with the list comprehension you want to reconstruct the original list of dicts with keys separately defined along with i.get('key'). This will let to work with the nested list value for keywords.
Iterate over the list and filter only the ones in common_keywords
Pass this list into collections.Counter to get your dict
Return it as a list with a single dict inside as you expect it to be

List of tuples to dictionary not working as expected

For some reason my small small brain is having problems with this, I have a list of tuples list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]. Im trying to move these values into a dictionary for parsing later. I have made a few attempts, below the latest of these and im not getting all results into the dict, the dict ends up with the last value iterated (its recreating the dict each time).
people = {}
list = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
for value in list:
people = {'person': [dict(item.split(":",1) for item in value)]}
You can try this one too:
inlist = [('name:john','age:25','location:brazil'),('name:terry','age:32','location:acme')]
d = []
for tup in inlist:
tempDict = {}
for elem in tup:
elem = elem.split(":")
tempDict.update({elem[0]:elem[1]})
d.append({'person':tempDict})
print(d)
Output:
[{'person': {'location': 'brazil', 'name': 'john', 'age': '25'}}, {'person': {'location': 'acme', 'name': 'terry', 'age': '32'}}]
If you want a dictionary with a key person and values the dictionaries with the people's info, then replace d.append({'person':tempDict}) with d.append(tempDict) and add d = {'person':d} right before printing.
Output:
{'person': [{'location': 'brazil', 'name': 'john', 'age': '25'}, {'location': 'acme', 'name': 'terry', 'age': '32'}]}
You can try this:
l = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
people = [{c:d for c, d in [i.split(':') for i in a]} for a in l]
Output:
[{'name': 'john', 'age': '25', 'location': 'brazil'}, {'person': 'terry', 'age': '32', 'location': 'acme'}]
First of all try not to call your list list. This name is protected in python and used usually to get a list out of iterators or ranges etc.
I would make a list of people first and then append each person to the people list as separate dictionary as follows:
people = []
my_list = [('name:john','age:25','location:brazil'),('person:terry','age:32','location:acme')]
for tup in my_list:
person = {}
for item in tup:
splitted = item.split(':')
person.update({splitted[0]:splitted[1]})
people.append(person)
The output then would be this:
[{'age': '25', 'location': 'brazil', 'name': 'john'},
{'age': '32', 'location': 'acme', 'person': 'terry'}]

Categories

Resources