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