Python dictionary no duplicate names - python

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

Related

How to exchange values inside a dict (based on Function Arguments)

Assuming the following dictionary in Python:
original_dict = {'place_01': 'Tom',
'place_02': 'John',
'place_03': 'Steve',
'place_04': 'Mark'}
I would like to define a function that allows me to exchange a defined pair values list.
My function should look like:
def change_position(mydict, change_from, change_to):
Passing the following arguments:
new_dict = change_position(original_dict, ['Tom','John'], ['Mark','Steve'])
Desidered result should be:
new_dict = {'place_01': 'Mark',
'place_02': 'Steve',
'place_03': 'John',
'place_04': 'Tom'}
basically:
'Tom' has been exchanged with 'Mark'
'John' has been exchanged Steve)
You can use a dictionary comprehension:
def change_position(mydict, c1, c2):
d = {**dict(zip(c1, c2)), **dict(zip(c2, c1))}
return {a:d[b] for a, b in mydict.items()}
original_dict = {'place_01': 'Tom', 'place_02': 'John', 'place_03': 'Steve', 'place_04': 'Mark'}
result = change_position(original_dict, ['Tom', 'John'], ['Mark', 'Steve'])
Output:
{'place_01': 'Mark', 'place_02': 'Steve', 'place_03': 'John', 'place_04': 'Tom'}
Requirement: values being unique in the dict
You need
a copy of my_dict to apply the changes
a reversed dict value > key to know where to apply the changes
Then iterate and swap
def change_position(mydict, change_from, change_to):
result = {**mydict}
mappings = {v: k for k, v in mydict.items()}
for val_from, val_to in zip(change_from, change_to):
key_from, key_to = mappings[val_from], mappings[val_to]
result[key_to], result[key_from] = mydict[key_from], mydict[key_to]
return result
Gives
original_dict = {'place_01': 'Tom', 'place_02': 'John', 'place_03': 'Steve', 'place_04': 'Mark'}
new_dict = change_position(original_dict, ['Tom', 'John'], ['Mark', 'Steve'])
print(new_dict) # {'place_01': 'Mark', 'place_02': 'Steve', 'place_03': 'John', 'place_04': 'Tom'}

Merge two dictionaries based on similarity excluding a key

I have the following three dictionaries in an array:
items = [
{
'FirstName': 'David',
'LastName': 'Smith',
'Language': set(['en'])
},
{
'FirstName': 'David',
'LastName': 'Smith',
'Language': set(['fr'])
},
{
'FirstName': 'Bob',
'LastName': 'Jones',
'Language': set(['en'])
} ]
I want to merge together these dictionaries if the two dictionaries are the same minus the specified key: and add that key together. If using the "Language" key it would merge the array into the following:
[ {
'FirstName': 'David',
'LastName': 'Smith',
'Language': set(['en','fr'])
},{
'FirstName': 'Bob',
'LastName': 'Jones',
'Language': set(['en'])
} ]
Here is what I'm currently doing:
from copy import deepcopy
def _merge_items_on_field(items, field):
'''Given an array of dicts, merge the
dicts together if they are the same except for the 'field'.
If merging dicts, add the unique values of that field together.'''
items = deepcopy(items)
items_merged_on_field = []
for num, item in enumerate(items):
# Remove that key/value from the dict
field_value = item.pop(field)
# Get an array of items *without* that field to compare against
items_without_field = deepcopy(items_merged_on_field)
map(lambda d: d.pop(field), items_without_field)
# If the dict item is found ("else"), add the fields together
# If not ("except"), then add in the dict item to the array
try:
index = items_without_field.index(item)
except ValueError:
item[field] = field_value
items_merged_on_field.append(item)
else:
items_merged_on_field[index][field] = items_merged_on_field[index][field].union(field_value)
return items_merged_on_field
>>> items = [{'LastName': 'Smith', 'Language': set(['en']), 'FirstName': 'David'}, {'LastName': 'Smith', 'Language': set(['fr']), 'FirstName': 'David'}, {'LastName': 'Jones', 'Language': set(['en']), 'FirstName': 'Bob'}]
>>> _merge_items_on_field(items, 'Language')
[{'LastName': 'Smith', 'Language': set(['fr', 'en']), 'FirstName': 'David'}, {'LastName': 'Jones', 'Language': set(['en']), 'FirstName': 'Bob'}]
This seems a bit complicated -- is there a better way to do this?
There are a couple of ways of doing this. The most painless method to my knowledge utilises the pandas library—in particular, a groupby + apply.
import pandas as pd
merged = (
pd.DataFrame(items)
.groupby(['FirstName', 'LastName'], sort=False)
.Language
.apply(lambda x: set.union(*x))
.reset_index()
.to_dict(orient='records')
)
print(merged)
[
{'FirstName': 'David', 'LastName': 'Smith', 'Language': {'en', 'fr'}},
{'FirstName': 'Bob', 'LastName': 'Jones', 'Language': {'en'}}
]
The other method (that I mentioned) uses itertools.groupby, but seeing as you have 30 columns to group on, I'd just recommend sticking to pandas.
If you want to turn this into a function,
def merge(items, field):
df = pd.DataFrame(items)
columns = df.columns.difference([field]).tolist()
return (
df.groupby(columns, sort=False)[field]
.apply(lambda x: set.union(*x))
.reset_index()
.to_dict(orient='records')
)
merged = merge(items, 'Language')
print(merged)
[
{'FirstName': 'David', 'LastName': 'Smith', 'Language': {'en', 'fr'}},
{'FirstName': 'Bob', 'LastName': 'Jones', 'Language': {'en'}}
]
You can use itertools.groupby:
import itertools
d = [{'FirstName': 'David', 'LastName': 'Smith', 'Language': {'en'}}, {'FirstName': 'David', 'LastName': 'Smith', 'Language': {'fr'}}, {'FirstName': 'Bob', 'LastName': 'Jones', 'Language': {'en'}}]
v = [[a, list(b)] for a, b in itertools.groupby(sorted(d, key=lambda x:x['FirstName']), key=lambda x:x['FirstName'])]
final_dict = [{**{'FirstName':a}, **{'LastName':(lambda x:[list(set(x)), x[0]][len(set(x)) == 1])([i['LastName'] for i in b])}, **{'Language':set([list(i['Language'])[0] for i in b])}} for a, b in v]
Output:
[{'FirstName': 'Bob', 'LastName': 'Jones', 'Language': {'en'}}, {'FirstName': 'David', 'LastName': 'Smith', 'Language': {'en', 'fr'}}]
If pandas is not an option:
from itertools import groupby
from functools import reduce
arr = [
{'FirstName': 'David', 'LastName': 'Smith', 'Language': set(['en'])},
{'FirstName': 'David', 'LastName': 'Smith', 'Language': set(['fr'])},
{'FirstName': 'David', 'LastName': 'Jones', 'Language': set(['sp'])}
]
def reduce_field(items, field, op=set.union, sort=False):
def _key(d):
return tuple((k, v) for k, v in d.items() if k != field)
if sort:
items = sorted(items, key=_key)
res = []
for k, g in groupby(items, key=_key):
d = dict(k)
d[field] = reduce(op, (el[field] for el in g))
res.append(d)
return res
reduce_field(arr, 'Language')
You can try it manually :
new_dict={}
#
#
#
d = [{'FirstName': 'David', 'LastName': 'Smith', 'Language': {'en'}},
{'FirstName': 'David', 'LastName': 'Smith', 'Language': {'fr'}},
{'FirstName': 'Bob', 'LastName': 'Jones', 'Language': {'en'}}]
for i in d:
if (i['FirstName'],i['LastName']) not in new_dict:
new_dict[(i['FirstName'],i['LastName'])]=i
else:
new_dict[(i['FirstName'],i['LastName'])]['Language']=set(list(new_dict[(i['FirstName'],i['LastName'])]['Language'])+list(i['Language']))
print(new_dict.values())
output:
# dict_values([{'FirstName': 'Bob',
# 'LastName': 'Jones',
# 'Language': {'en'}},
# {'FirstName': 'David',
# 'LastName': 'Smith',
# 'Language': {'fr', 'en'}}])

python: combine lists to dictionary with header

I want to combine two lists in to one dictionary type.
Name = ['John','Mary','Serena','Felicia']
Data = ['26','179','25','164','29','149','29','167']
desirable output in Json format
{"people":[{'Name': 'John',
'Age': '26',
'Height': '179'},
{'Name': 'Mary',
'Age': '25',
'Height': '164'}
{'Name': 'Serena',
'Age': '29',
'Height': '149'}
{'Name': 'Felicia',
'Age': '29',
'Height': '167'} ]
}
I try to combine with list1 = {k: 'Name' for k in Name} but the dictionary
shown 'John' = 'Name' which is reverse of what I need.
a couple of nested zips & slices do the trick to build dicts in a list comprehension, as value of the outer dict:
Name = ['John','Mary','Serena','Felicia']
Data = ['26','179','25','164','29','149','29','167']
result = {'people':[{'Name' : name, 'Age' : age, 'Height' : height}
for name,(age,height) in zip(Name,zip(Data[::2],Data[1::2]))]}
print(result)
prints:
{'people': [{'Name': 'John', 'Height': '179', 'Age': '26'}, {'Name': 'Mary', 'Height': '164', 'Age': '25'}, {'Name': 'Serena', 'Height': '149', 'Age': '29'}, {'Name': 'Felicia', 'Height': '167', 'Age': '29'}]}
if you don't want to create "hard" slices, use itertools.islice, also would be interesting to convert integer values as integer, which avoids the easy trap of lexicographical compare of integers as strings later on:
from itertools import islice
result = {'people':[{'Name' : name, 'Age' : int(age), 'Height' : int(height)}
for name,age,height in zip(Name,islice(Data,None,None,2),islice(Data,1,None,2))]}
(and also thanks to comments, no need to nest zip statements)
result:
{'people': [{'Height': 179, 'Age': 26, 'Name': 'John'},
{'Height': 164, 'Age': 25, 'Name': 'Mary'},
{'Height': 149, 'Age': 29, 'Name': 'Serena'},
{'Height': 167, 'Age': 29, 'Name': 'Felicia'}]}
Using zip:
Name = ['John','Mary','Serena','Felicia']
Data = ['26','179','25','164','29','149','29','167']
dct = {"people": [{'Name': i, 'Age': j, 'Height': k} for i, j, k in zip(Name, Data[::2], Data[1::2])]}
print(dct)
Output:
{'people': [{'Name': 'John', 'Age': '26', 'Height': '179'}, {'Name': 'Mary', 'Age': '25', 'Height': '164'}, {'Name': 'Serena', 'Age': '29', 'Height': '149'}, {'Name': 'Felicia', 'Age': '29', 'Height': '167'}]}
Here's an interesting approach.
>>> Name = ['John','Mary','Serena','Felicia']
>>> Data = ['26','179','25','164','29','149','29','167']
>>> keys = ['Name', 'Age', 'Height']
>>> it = iter(Data)
>>> {'people':[dict(zip(keys,i)) for i in zip(Name, it, it)]}
Can't make it too much more compact than this.
Ouput
{'people': [{'Name': 'John', 'Age': '26', 'Height': '179'}, {'Name': 'Mary', 'Age': '25', 'Height': '164'}, {'Name': 'Serena', 'Age': '29', 'Height': '149'}, {'Name': 'Felicia', 'Age': '29', 'Height': '167'}]}

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

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

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
>>>

Categories

Resources