Python 3 : Print a list that's inside a list - python

I cannot seem to print a list that's within a list. I know that it goes wrong when I repeat the for loop for key and values. I was wondering if there is a way to make so that it prints each troop name for each platoon.
import random, math
first_name = ['John', 'Clay', 'Gordy', 'Erv', 'Sebastian', 'Tilly', 'Jesse', 'Alban', 'Oliver', 'Samuel', 'Joseph', 'Gregory', 'Alair', 'Gilbert', 'Nigel', 'Gibson', 'Oliver', 'Ralph', 'Rufus', 'Garson', 'Ferrol', 'Miles', 'Chilton', 'Charles', 'Gordon', 'Edward', 'Gerald', 'Shel', 'Dean', 'Noah', 'Herbert', 'Humphrey', 'Hanley', 'Ruben', 'Gibson', 'Jonathan', 'Fisk', 'Harold', 'Cristian', 'Andy', 'Kyne', 'Garson', 'Jackson', 'Maitland', 'George', 'Ford', 'Raleigh', 'Fox', 'Forbes', 'Yeardleigh', 'Gordon', 'Francis', 'Jett', 'Fairfax', 'Ford', 'Haines', 'Benjamin', 'Samuel', 'Alban', 'Chip', 'Eric', 'Alban', 'Charles', 'Sherman', 'Harrison', 'Malcolm', 'Chilton', 'Eliah', 'Junior', 'Mark', 'Bond', 'Chick', 'Emmanuel', 'Raleigh', 'Brigham', 'Archibald', 'Gates', 'Filbert', 'Barnabas', 'Geoffrey', 'Terence', 'Stacy', 'Forbes', 'Gomer', 'Fairly', 'Archer', 'Oscar', 'William', 'Ernes', 'Chill', 'Gregory', 'Weylin', 'Holt', 'Clayland', 'Gram', 'Forbes', 'Set', 'Hartwell', 'Luke', 'Garson']
last_name = ['Mitchell', 'Martin', 'Anderson', 'Patel', 'Young', 'Jackson', 'Ward', 'Jackson', 'Patel', 'Walker', 'Lee', 'Patel', 'Johnson', 'Thomas', 'Morris', 'Watson', 'Martin', 'Roberts', 'Jones', 'Lewis', 'Morgan', 'Wood', 'Lee', 'White', 'James', 'Scott', 'Young', 'Clarke', 'Edwards', 'Smith', 'Jackson', 'Turner', 'Ward', 'Hall', 'Anderson', 'Walker', 'Scott', 'Mitchell', 'Williams', 'Young', 'Allen', 'Huges', 'Phillips', 'Robinson', 'Evans', 'Thomas', 'Taylor', 'Robinson', 'Harris', 'Ward', 'Johnson', 'Anderson', 'Scott', 'Martin', 'Allen', 'Clark', 'Jones', 'Wilson', 'Phillips', 'Lewis', 'Jones', 'Anderson', 'Wright', 'Clark', 'White', 'Lewis', 'Patel', 'Wilson', 'Wilson', 'Taylor', 'Williams', 'Turner', 'Smith', 'Davies', 'Harrison', 'Thompson', 'Anderson', 'Harris', 'Brown', 'Lewis', 'Phillips', 'Watson', 'Harrison', 'Harris', 'Wilson', 'Davies', 'Brown', 'Huges', 'Parker', 'King', 'Wright', 'Anderson', 'Anderson', 'Phillips', 'Harrison', 'Walker', 'Wood', 'Young', 'Clark', 'Jones']
troops = []
temp_platoon = []
platoons = []
platoon_names = ['Alpha', 'Beta', 'Charlie', 'Delta', 'Echo', 'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet', 'Kilo', 'Lima', 'Mike', 'November', 'Oscar', 'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango', 'Uniform', 'Victor', 'Whiskey', 'X-Ray', 'Yankee', 'Zulu']
a = 0
while a < 90:
s_name = random.choice(first_name) + " " + random.choice(last_name)
s_number = 100
troops.append((s_name, s_number))
a = a + 1
platoon_number = 1
troop_number = 0
for key in troops :
troop_number = troop_number + 1
a = troops.pop(0)
temp_platoon.append((a))
if troop_number == 30:
# Platoon n is the name of platoon
# Platoon is the actual platoon
platoon_number = platoon_number + 1
platoon = platoon_names.pop(0)
platoon_n = platoon
platoon = []
for k, v in temp_platoon:
platoon.append((k, v))
print("Added {} to platoon {}. He has {} health".format(k, platoon_n, v))
platoons.append((platoon_n))
troop_number = 0
def read ():
print("Reading")
for key in platoons:
print(key)
for w in key:
print(w)
print(platoons)
read()
Also note im teaching myself python 3. I have only just started touching on classes.

I may have it wrong, but I think you might want it to look something like this:
import random
first_name = ['John', 'Clay', 'Gordy', 'Erv']
last_name = ['Mitchell', 'Martin', 'Anderson', 'Patel']
platoon_names = ['Alpha', 'Beta', 'Charlie', 'Delta']
platoons = dict()
using a list comprehension we can completely replace the while loop. every soldier is a tuple (name, health)... I presume you wanted this, but if not just remove the 100).
troops = [(random.choice(first_name) + " " + random.choice(last_name), 100) for r in range(90)]
the following helper function is lifter from here
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i+n]
we now populate the platoons dictionary (the key is the platoon name, while the value is a list containing the soldiers).
for number, platoon in enumerate(list(chunks(troops,3))):
platoons[platoon_names[number]] = platoon
use iteritems to iterate over a dictionary.
def read ():
print("Reading")
for platoon, troops in platoons.iteritems():
print("--------Platoon name--------")
print(platoon)
print("--------troops--------")
for (name, health) in troops:
print(name)
and this is what we get.
>>> read()
Reading
--------Platoon name--------
Alpha
--------troops--------
John Anderson
Clay Mitchell
Erv Martin
--------Platoon name--------
Beta
--------troops--------
Clay Anderson
Clay Anderson
Clay Patel
--------Platoon name--------
Delta
--------troops--------
John Anderson
Gordy Martin
John Anderson
--------Platoon name--------
Charlie
--------troops--------
Clay Mitchell
Clay Patel
Clay Patel
>>>

Related

Python dictionary no duplicate names

def sort_dictionary(dict: dict) -> dict:
return {k: sorted(v) for k, v in dict.items()}
def create_dictionary_with_hobbies(data: str) -> dict:
"""Create dictionary about hobbies and their hobbyists ie. {hobby1: [name1, name2, ...], hobby2: [...]}."""
result = {}
for line in data.split('\n'):
name, hobby = line.split(":")
result.setdefault(hobby, []).append(name)
result = sort_dictionary(result)
return result
if __name__ == '__main__':
sample_data = """Jack:crafting\nPeter:hiking\nWendy:gaming\nMonica:tennis\nChris:origami\nSophie:sport\nMonica:design\nCarmen:sport\nChris:sport\nMonica:skateboarding\nCarmen:cooking\nWendy:photography\nMonica:tennis\nCooper:yoga\nWendy:sport\nCooper:movies\nMonica:theatre\nCooper:yoga\nChris:gaming\nMolly:fishing\nJack:skateboarding\nWendy:fishing\nJack:drawing\nMonica:baking\nSophie:baking\nAlfred:driving\nAlfred:shopping\nAlfred:crafting\nJack:drawing\nCarmen:shopping\nCarmen:driving\nPeter:drawing\nCarmen:shopping\nWendy:fitness\nAlfred:travel\nJack:origami\nSophie:design\nJack:pets\nCarmen:dance\nAlfred:baking\nSophie:sport\nPeter:gaming\nJack:skateboarding\nCooper:football\nAlfred:sport\nCooper:fitness\nChris:yoga\nWendy:football\nMolly:design\nJack:hiking\nMonica:pets\nCarmen:photography\nJack:baking\nPeter:driving\nChris:driving\nCarmen:driving\nPeter:theatre\nMolly:hiking\nWendy:puzzles\nJack:crafting\nPeter:photography\nCarmen:theatre\nSophie:crafting\nCarmen:cooking\nAlfred:gaming\nPeter:theatre\nCooper:hiking\nChris:football\nChris:pets\nJack:football\nMonica:skateboarding\nChris:driving\nCarmen:pets\nCooper:gaming\nChris:hiking\nJack:cooking\nPeter:fishing\nJack:gaming\nPeter:origami\nCarmen:movies\nSophie:driving\nJack:sport\nCarmen:theatre\nWendy:shopping\nCarmen:pets\nWendy:gaming\nSophie:football\nWendy:theatre\nCarmen:football\nMolly:theatre\nPeter:theatre\nMonica:flowers\nMolly:skateboarding\nPeter:driving\nSophie:travel\nMonica:photography\nCooper:cooking\nJack:fitness\nPeter:cooking\nChris:gaming"""
print(create_dictionary_with_hobbies(sample_data))
Result:
{'crafting': ['Alfred', 'Jack', 'Jack', 'Sophie'], 'hiking': ['Chris', 'Cooper', 'Jack', 'Molly', 'Peter'], 'gaming': ['Alfred', 'Chris', 'Chris', 'Cooper', 'Jack', 'Peter', 'Wendy', 'Wendy'], 'tennis': ['Monica', 'Monica'], 'origami': ['Chris', 'Jack', 'Peter'], 'sport': ['Alfred', 'Carmen', 'Chris', 'Jack', 'Sophie', 'Sophie', 'Wendy'], 'design': ['Molly', 'Monica', 'Sophie'], 'skateboarding': ['Jack', 'Jack', 'Molly', 'Monica', 'Monica'], 'cooking': ['Carmen', 'Carmen', 'Cooper', 'Jack', 'Peter'], 'photography': ['Carmen', 'Monica', 'Peter', 'Wendy'], 'yoga': ['Chris', 'Cooper', 'Cooper'], 'movies': ['Carmen', 'Cooper'], 'theatre': ['Carmen', 'Carmen', 'Molly', 'Monica', 'Peter', 'Peter', 'Peter', 'Wendy'], 'fishing': ['Molly', 'Peter', 'Wendy'], 'drawing': ['Jack', 'Jack', 'Peter'], 'baking': ['Alfred', 'Jack', 'Monica', 'Sophie'], 'driving': ['Alfred', 'Carmen', 'Carmen', 'Chris', 'Chris', 'Peter', 'Peter', 'Sophie'], 'shopping': ['Alfred', 'Carmen', 'Carmen', 'Wendy'], 'fitness': ['Cooper', 'Jack', 'Wendy'], 'travel': ['Alfred', 'Sophie'], 'pets': ['Carmen', 'Carmen', 'Chris', 'Jack', 'Monica'], 'dance': ['Carmen'], 'football': ['Carmen', 'Chris', 'Cooper', 'Jack', 'Sophie', 'Wendy'], 'puzzles': ['Wendy'], 'flowers': ['Monica']}
Maybe you could suggest what function can add to remove duplicates. Let's say in the first crafting answer there are two Jacks, but there should be one. But the alphabetical order of names should also be preserved, like it now is.
I understand that no one will write the code for me, but it would be nice to get an answer to this question.
You can just change
result.setdefault(hobby, []).append(name)
to
result.setdefault(hobby, set()).add(name)
Set will be sorted by sorted() function.
Adding the items to a dict with set values will remove duplicates. You can then convert the sets to lists and sort them.
hobbies_dict = {}
for item in sample_data.split():
v, k = item.split(':')
if k not in hobbies_dict:
hobbies_dict[k] = set([v])
else:
hobbies_dict[k].add(v)
for k,v in hobbies_dict.items(): # convert set to list and order items
hobbies_dict[k] = sorted(list(v))
For Python 3.7 or later you can use the feature that dictionaries maintain order (and that duplicate keys are not allowed). Which means you can simply use:
for k, v in mydict.items():
mydict[k] = list(dict.fromkeys(v))
which will remove duplicates from the lists in the dictionary

Creating undirected unweighted graph from dictionary containing neighborhood relationship

I have a Python dictionary that looks like this:
{'Aitkin': ['Carlton', 'Cass', 'Crow Wing', 'Itasca',
'Kanabec', 'Mille Lacs', 'Pine', 'St. Louis'], 'Anoka':
['Chisago', 'Hennepin', 'Isanti', 'Ramsey', 'Sherburne',
'Washington'], 'Becker': ['Clay', 'Clearwater', 'Hubbard',
'Mahnomen', 'Norman', 'Otter Tail', 'Wadena'], 'Beltrami':
['Cass', 'Clearwater', 'Hubbard', 'Itasca', 'Koochiching',
'Lake of the Woods', 'Marshall', 'Pennington', 'Roseau'],
'Benton': ['Mille Lacs', 'Morrison', 'Sherburne', 'Stearns'], 'Big
Stone': ['Lac qui Parle', 'Stevens', 'Swift', 'Traverse'], 'Blue
Earth': ['Brown', 'Faribault', 'Le Sueur', 'Martin',
'Nicollet', 'Waseca', 'Watonwan'], 'Brown': ['Blue Earth',
'Cottonwood', 'Nicollet', 'Redwood', 'Renville', 'Watonwan'],
'Carlton': ['Aitkin', 'Pine', 'St. Louis'], 'Carver': ['Hennepin',
'McLeod', 'Scott', 'Sibley', 'Wright'], 'Cass': ['Aitkin',
'Beltrami', 'Crow Wing', 'Hubbard', 'Itasca', 'Morrison',
'Todd', 'Wadena'], 'Chippewa': ['Kandiyohi', 'Lac qui Parle',
'Renville', 'Swift', 'Yellow Medicine'], 'Chisago': ['Anoka',
'Isanti', 'Kanabec', 'Pine', 'Washington'], 'Clay': ['Becker',
'Norman', 'Otter Tail', 'Wilkin'], 'Clearwater': ['Becker',
'Beltrami', 'Hubbard', 'Mahnomen', 'Pennington', 'Polk'],
'Cook': ['Lake'], 'Cottonwood': ['Brown', 'Jackson', 'Murray',
'Nobles', 'Redwood', 'Watonwan'], 'Crow Wing': ['Aitkin', 'Cass',
'Mille Lacs', 'Morrison'], 'Dakota': ['Goodhue', 'Hennepin',
'Ramsey', 'Rice', 'Scott', 'Washington'], 'Dodge': ['Goodhue',
'Mower', 'Olmsted', 'Rice', 'Steele'], 'Douglas': ['Grant', 'Otter
Tail', 'Pope', 'Stearns', 'Stevens', 'Todd'], 'Faribault': ['Blue
Earth', 'Freeborn', 'Martin', 'Waseca'], 'Fillmore': ['Houston',
'Mower', 'Olmsted', 'Winona'], 'Freeborn': ['Faribault', 'Mower',
'Steele', 'Waseca'], 'Goodhue': ['Dakota', 'Dodge', 'Olmsted',
'Rice', 'Wabasha'], 'Grant': ['Douglas', 'Otter Tail', 'Pope',
'Stevens', 'Traverse', 'Wilkin'], 'Hennepin': ['Anoka', 'Carver',
'Dakota', 'Ramsey', 'Scott', 'Sherburne', 'Wright'],
'Houston': ['Fillmore', 'Winona'], 'Hubbard': ['Becker', 'Beltrami',
'Cass', 'Clearwater', 'Wadena'], 'Isanti': ['Anoka', 'Chisago',
'Kanabec', 'Mille Lacs', 'Pine', 'Sherburne'], 'Itasca': ['Aitkin',
'Beltrami', 'Cass', 'Koochiching', 'St. Louis'], 'Jackson':
['Cottonwood', 'Martin', 'Nobles', 'Watonwan'], 'Kanabec': ['Aitkin',
'Chisago', 'Isanti', 'Mille Lacs', 'Pine'], 'Kandiyohi': ['Chippewa',
'Meeker', 'Pope', 'Renville', 'Stearns', 'Swift'], 'Kittson':
['Marshall', 'Roseau'], 'Koochiching': ['Beltrami', 'Itasca', 'Lake
of the Woods', 'St. Louis'], 'Lac qui Parle': ['Big Stone',
'Chippewa', 'Swift', 'Yellow Medicine'], 'Lake': ['Cook', 'St.
Louis'], 'Lake of the Woods': ['Beltrami', 'Koochiching', 'Roseau'],
'Le Sueur': ['Blue Earth', 'Nicollet', 'Rice', 'Scott', 'Sibley',
'Waseca'], 'Lincoln': ['Lyon', 'Pipestone', 'Yellow Medicine'],
'Lyon': ['Lincoln', 'Murray', 'Pipestone', 'Redwood', 'Yellow
Medicine'], 'Mahnomen': ['Becker', 'Clearwater', 'Norman', 'Polk'],
'Marshall': ['Beltrami', 'Kittson', 'Pennington', 'Polk', 'Roseau'],
'Martin': ['Blue Earth', 'Faribault', 'Jackson', 'Watonwan'],
'McLeod': ['Carver', 'Meeker', 'Renville', 'Sibley', 'Wright'],
'Meeker': ['Kandiyohi', 'McLeod', 'Renville', 'Stearns', 'Wright'],
'Mille Lacs': ['Aitkin', 'Benton', 'Crow Wing', 'Isanti',
'Kanabec', 'Morrison', 'Sherburne'], 'Morrison': ['Benton',
'Cass', 'Crow Wing', 'Mille Lacs', 'Stearns', 'Todd'], 'Mower':
['Dodge', 'Fillmore', 'Freeborn', 'Olmsted', 'Steele'], 'Murray':
['Cottonwood', 'Lyon', 'Nobles', 'Pipestone', 'Redwood', 'Rock'],
'Nicollet': ['Blue Earth', 'Brown', 'Le Sueur', 'Renville', 'Sibley'],
'Nobles': ['Cottonwood', 'Jackson', 'Murray', 'Rock'], 'Norman':
['Becker', 'Clay', 'Mahnomen', 'Polk'], 'Olmsted': ['Dodge',
'Fillmore', 'Goodhue', 'Mower', 'Wabasha', 'Winona'], 'Otter Tail':
['Becker', 'Clay', 'Douglas', 'Grant', 'Wadena', 'Wilkin'],
'Pennington': ['Beltrami', 'Clearwater', 'Marshall', 'Polk', 'Red
Lake'], 'Pine': ['Aitkin', 'Carlton', 'Chisago', 'Isanti',
'Kanabec'], 'Pipestone': ['Lincoln', 'Lyon', 'Murray', 'Rock'],
'Polk': ['Clearwater', 'Mahnomen', 'Marshall', 'Norman',
'Pennington', 'Red Lake'], 'Pope': ['Douglas', 'Grant',
'Kandiyohi', 'Stearns', 'Stevens', 'Swift'], 'Ramsey': ['Anoka',
'Dakota', 'Hennepin', 'Washington'], 'Red Lake': ['Pennington',
'Polk'], 'Redwood': ['Brown', 'Cottonwood', 'Lyon', 'Murray',
'Renville', 'Yellow Medicine'], 'Renville': ['Brown', 'Chippewa',
'Kandiyohi', 'McLeod', 'Meeker', 'Nicollet', 'Redwood',
'Sibley', 'Yellow Medicine'], 'Rice': ['Dakota', 'Dodge',
'Goodhue', 'Le Sueur', 'Scott', 'Steele', 'Waseca'], 'Rock':
['Murray', 'Nobles', 'Pipestone'], 'Roseau': ['Beltrami', 'Kittson',
'Lake of the Woods', 'Marshall'], 'Scott': ['Carver', 'Dakota',
'Hennepin', 'Le Sueur', 'Rice', 'Sibley'], 'Sherburne': ['Anoka',
'Benton', 'Hennepin', 'Isanti', 'Mille Lacs', 'Stearns',
'Wright'], 'Sibley': ['Carver', 'Le Sueur', 'McLeod', 'Nicollet',
'Renville', 'Scott'], 'St. Louis': ['Aitkin', 'Carlton', 'Itasca',
'Koochiching', 'Lake'], 'Stearns': ['Benton', 'Douglas',
'Kandiyohi', 'Meeker', 'Morrison', 'Pope', 'Sherburne',
'Todd', 'Wright'], 'Steele': ['Dodge', 'Freeborn', 'Mower', 'Rice',
'Waseca'], 'Stevens': ['Big Stone', 'Douglas', 'Grant', 'Pope',
'Swift', 'Traverse'], 'Swift': ['Big Stone', 'Chippewa',
'Kandiyohi', 'Lac qui Parle', 'Pope', 'Stevens'], 'Todd':
['Cass', 'Douglas', 'Morrison', 'Otter Tail', 'Stearns', 'Wadena'],
'Traverse': ['Big Stone', 'Grant', 'Stevens', 'Wilkin'], 'Wabasha':
['Goodhue', 'Olmsted', 'Winona'], 'Wadena': ['Becker', 'Cass',
'Hubbard', 'Otter Tail', 'Todd'], 'Waseca': ['Blue Earth',
'Faribault', 'Freeborn', 'Le Sueur', 'Rice', 'Steele'],
'Washington': ['Anoka', 'Chisago', 'Dakota', 'Ramsey'], 'Watonwan':
['Blue Earth', 'Brown', 'Cottonwood', 'Jackson', 'Martin'], 'Wilkin':
['Clay', 'Grant', 'Otter Tail', 'Traverse'], 'Winona': ['Fillmore',
'Houston', 'Olmsted', 'Wabasha'], 'Wright': ['Carver', 'Hennepin',
'McLeod', 'Meeker', 'Sherburne', 'Stearns'], 'Yellow Medicine':
['Chippewa', 'Lac qui Parle', 'Lincoln', 'Lyon', 'Redwood',
'Renville']}
The keys in the dictionary represent the nodes, while the values(lists) represent nodes of neighbors of the key. This is an undirected unweighted graph.
Is there some function to implement this in networkx or some network analysis or graph-related libraries?
You can use the nx.Graph constructor -- it will add additional nodes if they don't appear as keys in the original dictionary (data represents the dictionary in the original question):
import networkx as nx
graph = nx.Graph(data)

Is there a way to print a variable x times depending on what number the user wrote in the input to decide x? [Python 3.8]

I'm making a random name generator using the random module. I'm using the most popular first female and male names along with popular last names to generate two names, one male, and one female:
firstnames = ['Liam', 'Noah', 'William', 'Oliver', 'Benjamin', 'Elijah', 'Lucas', 'Mason', 'Logan']
lastnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Garcia', 'Miller', 'Davis', 'Wilson', 'Martinez']
print(random.choice(firstnames) + " " + random.choice(lastnames))
firstfemnames = ['Emma','Olivia','Ava', 'Isabella', 'Sophia', 'Charlotte', 'Mia', 'Amelia', 'Harper', 'Evelyn']
lastfemnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Garcia', 'Miller', 'Davis', 'Wilson', 'Martinez']
print(random.choice(firstfemnames) + " " + random.choice(lastfemnames))
So the output, after being printed, would give two random names like this:
Noah Jones
Evelyn Smith
I want to make an input for how many other random names they want after those two are printed; for example, if you make an input after printing the first two random names [Noah Jones and Evelyn Smith], I want to make an input for numbers, so if you input 2, another two random names are printed. How do I do this?
import random
firstnames = ['Liam', 'Noah', 'William', 'Oliver', 'Benjamin', 'Elijah', 'Lucas', 'Mason', 'Logan']
lastnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Garcia', 'Miller', 'Davis', 'Wilson', 'Martinez']
firstfemnames = ['Emma','Olivia','Ava', 'Isabella', 'Sophia', 'Charlotte', 'Mia', 'Amelia', 'Harper', 'Evelyn']
lastfemnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Garcia', 'Miller', 'Davis', 'Wilson', 'Martinez']
def printMaleName():
print(random.choice(firstnames) + " " + random.choice(lastnames))
def printFemaleName():
print(random.choice(firstfemnames) + " " + random.choice(lastfemnames))
male = int(input("Enter the number of male names you want: "))
female = int(input("Enter the number of female names you want: "))
for _ in range (male):
printMaleName()
for _ in range(female):
printFemaleName()
For getting the number of pairs, use the input() function
For acting on it, use a for loop.
import random
firstnames = ['Liam', 'Noah', 'William', 'Oliver', 'Benjamin', 'Elijah', 'Lucas', 'Mason', 'Logan']
lastnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Garcia', 'Miller', 'Davis', 'Wilson', 'Martinez']
print(random.choice(firstnames) + " " + random.choice(lastnames))
firstfemnames = ['Emma','Olivia','Ava', 'Isabella', 'Sophia', 'Charlotte', 'Mia', 'Amelia', 'Harper', 'Evelyn']
lastfemnames = ['Smith', 'Johnson', 'Williams', 'Jones', 'Garcia', 'Miller', 'Davis', 'Wilson', 'Martinez']
print(random.choice(firstfemnames) + " " + random.choice(lastfemnames))
noofchildren=input()
for i in noofchildren:
print(random.choice(firstfemnames) + " " +
random.choice(lastfemnames))

Create a list of dictionaries from a list of keys and multiple lists of values

My solution
keys = ['FirstName', 'LastName', 'ID']
name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']
dictList = []
dictList.append(dict(zip(keys, name1)))
dictList.append(dict(zip(keys, name2)))
dictList.append(dict(zip(keys, name3)))
Works fine, but is there any other solution, because I will have at least 20000 names, so I am looking how to improve this.
Place all your "name" sublists into the parent list names. Then you can easily use list comprehension:
keys = ['FirstName', 'LastName', 'ID']
names = [
['Michael', 'Jordan', '224567'],
['Kyle', 'Hynes', '294007'],
['Josef', 'Jones', '391107']
]
dictList = [{k:v for k,v in zip(keys, n)} for n in names]
print(dictList)
The output:
[{'FirstName': 'Michael', 'LastName': 'Jordan', 'ID': '224567'}, {'FirstName': 'Kyle', 'LastName': 'Hynes', 'ID': '294007'}, {'FirstName': 'Josef', 'LastName': 'Jones', 'ID': '391107'}]
Do you really need a dictionary? Why not just use a namedtuple:
>>> from collections import namedtuple
>>> Employee = namedtuple('Employee', 'FirstName, LastName, ID')
>>> names_list = [['Michael', 'Jordan', '224567'], ['Kyle', 'Hynes', '294007'], ['Josef', 'Jones', '391107']]
>>> employee_list = map(Employee._make, names_list)
>>> employee_list[0].FirstName
'Michael'
>>> pprint(employee_list)
[Employee(FirstName='Michael', LastName='Jordan', ID='224567'),
Employee(FirstName='Kyle', LastName='Hynes', ID='294007'),
Employee(FirstName='Josef', LastName='Jones', ID='391107')]
pandas makes this too easy.
import pandas as pd
keys = ['FirstName', 'LastName', 'ID']
name1 = ['Michael', 'Jordan', '224567']
name2 = ['Kyle', 'Hynes', '294007']
name3 = ['Josef', 'Jones', '391107']
doc_list = [name1,name2,name3]
df = pd.DataFrame(doc_list,columns = keys)
So you'll have a DataFrame like this:
FirstName LastName ID
0 Michael Jordan 224567
1 Kyle Hynes 294007
2 Josef Jones 391107
If your names are already in a file,read_csv would be better.
pd.read_csv("file_name.csv",header=keys)//remove the header parameter if it is present in your csv.
You should append your dictionaries to the list inside a loop, like this:
In [1152]: names = [name1, name2, name3]
In [1153]: d = []
In [1154]: for name in names:
...: d.append(dict(zip(keys, name)))
...:
In [1155]: d
Out[1155]:
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
{'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
{'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]
Or, if you prefer, a list comprehension:
In [1160]: d = [dict(zip(keys, name)) for name in names]
In [1161]: d
Out[1161]:
[{'FirstName': 'Michael', 'ID': '224567', 'LastName': 'Jordan'},
{'FirstName': 'Kyle', 'ID': '294007', 'LastName': 'Hynes'},
{'FirstName': 'Josef', 'ID': '391107', 'LastName': 'Jones'}]

Matching keys in different lists of dicts

I have a csv.DictReader instance of dicts and a list of dicts.
instance:
{'Salary': '3000', 'Name': 'James Jones', 'GameInfo': 'Den#Cle 07:30PM ET',
'AvgPointsPerGame': '4.883', 'teamAbbrev': 'Cle', 'Position': 'SG'}
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl#Dal 09:00PM ET',
'AvgPointsPerGame': '13.161', 'teamAbbrev': 'Dal', 'Position': 'SF'}
list:
[
{'playername': 'Justin Anderson', 'points': '6.94'},
{'playername': 'DeAndre Liggins', 'points': '11.4'},
]
I cannot figure out how to iterate over these lists of dictionaries, match the Name and playername keys, then spit the ['Name'] from one dict and the ['points'] from the matching dict. In the example above I would match Justin Anderson from the two sets of dicts then print out Justin Anderson, 6.94
The core of the app takes 2 CSV's and makes them lists of dicts.
It's not really efficient this way but it wouldn't require any preprocessing:
# Instead of your CSVReader:
dicts = [{'Salary': '3000', 'Name': 'James Jones', 'GameInfo': 'Den#Cle 07:30PM ET', 'AvgPointsPerGame': '4.883', 'teamAbbrev': 'Cle', 'Position': 'SG'},
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl#Dal 09:00PM ET', 'AvgPointsPerGame': '13.161', 'teamAbbrev': 'Dal', 'Position': 'SF'}]
list_of_dicts = [
{'playername': 'Justin Anderson', 'points': '6.94'},
{'playername': 'DeAndre Liggins', 'points': '11.4'},
]
# For each dictionary in the CSVReader
for dct in dicts:
# For each dictionary in your list of dictionaries
for subdict in list_of_dicts:
# Check if the name and playername matches
if dct['Name'] == subdict['playername']:
# I just print out the results, you need to do your logic here
print(dct['Name'])
print(dct)
print('matching')
print(subdict)
and this prints:
Justin Anderson
{'Salary': '3000', 'Name': 'Justin Anderson', 'GameInfo': 'Orl#Dal 09:00PM ET', 'AvgPointsPerGame': '13.161', 'Position': 'SF', 'teamAbbrev': 'Dal'}
matching
{'playername': 'Justin Anderson', 'points': '6.94'}
If you want it faster than you should preprocess your list of dictionaries so that you can simply lookup the playername:
>>> dict_of_dicts = {dct['playername']: dct for dct in list_of_dicts}
>>> dict_of_dicts
{'DeAndre Liggins': {'playername': 'DeAndre Liggins', 'points': '11.4'},
'Justin Anderson': {'playername': 'Justin Anderson', 'points': '6.94'}}
Then the loop simplifies to:
for dct in dicts:
if dct['Name'] in dict_of_dicts:
print(dct['Name'])
print(dct)
print('matching')
print(dict_of_dicts[dct['Name']])
giving the same result.

Categories

Resources