I need it to stop cloning and add the new dictionaries to the list
I even tried update for updating dictionaries but did not work
import random
# This line creates a set with 6 random numbers
#We use a 22 range or similar, otherwise the players will not get enough correct numbers for creating a solution in a learning enviroment.
lottery_numbers = set(random.sample(range(22), 6))
# Here are your players; they all decided to get their numbers randomly find out who has the most numbers matching lottery_numbers!
players = [
{'name': 'Rolf', 'numbers': set(random.sample(range(22), 6))},
{'name': 'Charlie', 'numbers':set(random.sample(range(22), 6))},
{'name': 'Anna', 'numbers': set(random.sample(range(22), 6))},
{'name': 'Jen', 'numbers': set(random.sample(range(22), 6))}
]
num_player = [1000]
dicc_A = {}
print("Lottery numbers ", lottery_numbers)
print("")
for a in players:
print("Line by line",a)
print("")
for i,j in a.items():
if i == "name":
dicc_A["Name"] = j
print("name Dicc: ", dicc_A)
if i == "numbers":
dicc_A["Num"] = j.intersection(lottery_numbers)
print(" xxxxxxxxxx NUMPLAYER before APPEND inside FOR ",num_player)
print("******number Dicc: ", dicc_A)
num_player.append(dicc_A)
print("")
print(" ///////// NUMPLAYER after APPEND inside FOR ",num_player)
This is the output****************
Lottery numbers {5, 9, 13, 14, 19, 20}
Line by line {'name': 'Rolf', 'numbers': {2, 3, 5, 11, 12, 19}}
name Dicc: {'Name': 'Rolf'}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000]
******number Dicc: {'Name': 'Rolf', 'Num': {19, 5}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {19, 5}}]
Line by line {'name': 'Charlie', 'numbers': {0, 4, 7, 8, 17, 20}}
name Dicc: {'Name': 'Charlie', 'Num': {19, 5}}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000, {'Name': 'Charlie', 'Num': {20}}]
******number Dicc: {'Name': 'Charlie', 'Num': {20}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Charlie', 'Num': {20}}, {'Name': 'Charlie', 'Num': {20}}]
Line by line {'name': 'Anna', 'numbers': {4, 5, 6, 10, 16, 17}}
name Dicc: {'Name': 'Anna', 'Num': {20}}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000, {'Name': 'Anna', 'Num': {5}}, {'Name': 'Anna', 'Num': {5}}]
******number Dicc: {'Name': 'Anna', 'Num': {5}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Anna', 'Num': {5}}, {'Name': 'Anna', 'Num': {5}}, {'Name': 'Anna', 'Num': {5}}]
Line by line {'name': 'Jen', 'numbers': {2, 4, 5, 8, 9, 10}}
name Dicc: {'Name': 'Jen', 'Num': {5}}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000, {'Name': 'Jen', 'Num': {9, 5}}, {'Name': 'Jen', 'Num': {9, 5}}, {'Name': 'Jen', 'Num': {9, 5}}]
******number Dicc: {'Name': 'Jen', 'Num': {9, 5}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Jen', 'Num': {9, 5}}, {'Name': 'Jen', 'Num': {9, 5}}, {'Name': 'Jen', 'Num': {9, 5}}, {'Name': 'Jen', 'Num': {9, 5}}]
Oh sorry. now I see to append a dictionary to a list you need to create a copy
So the solution was simply this
import random
# This line creates a set with 6 random numbers
#We use a 22 range or similar, otherwise the players will not get enough correct numbers for creating a solution in a learning enviroment.
lottery_numbers = set(random.sample(range(22), 6))
# Here are your players; they all decided to get their numbers randomly find out who has the most numbers matching lottery_numbers!
players = [
{'name': 'Rolf', 'numbers': set(random.sample(range(22), 6))},
{'name': 'Charlie', 'numbers':set(random.sample(range(22), 6))},
{'name': 'Anna', 'numbers': set(random.sample(range(22), 6))},
{'name': 'Jen', 'numbers': set(random.sample(range(22), 6))}
]
num_player = [1000]
dicc_A = {}
print("Lottery numbers ", lottery_numbers)
print("")
for a in players:
print("Line by line",a)
print("")
for i,j in a.items():
if i == "name":
dicc_A["Name"] = j
print("name Dicc: ", dicc_A)
if i == "numbers":
dicc_A["Num"] = j.intersection(lottery_numbers)
print(" xxxxxxxxxx NUMPLAYER before APPEND inside FOR ",num_player)
print("******number Dicc: ", dicc_A)
dictionary_copy = dicc_A.copy()
num_player.append(dictionary_copy)
print("")
print(" ///////// NUMPLAYER after APPEND inside FOR ",num_player)
print("")
print("")
*************outputs
Lottery numbers {2, 7, 12, 17, 20, 21}
Line by line {'name': 'Rolf', 'numbers': {3, 4, 9, 12, 13, 14}}
name Dicc: {'Name': 'Rolf'}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000]
******number Dicc: {'Name': 'Rolf', 'Num': {12}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}]
Line by line {'name': 'Charlie', 'numbers': {4, 8, 10, 12, 13, 18}}
name Dicc: {'Name': 'Charlie', 'Num': {12}}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}]
******number Dicc: {'Name': 'Charlie', 'Num': {12}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}, {'Name': 'Charlie', 'Num': {12}}]
Line by line {'name': 'Anna', 'numbers': {10, 14, 16, 17, 20, 21}}
name Dicc: {'Name': 'Anna', 'Num': {12}}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}, {'Name': 'Charlie', 'Num': {12}}]
******number Dicc: {'Name': 'Anna', 'Num': {17, 20, 21}}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}, {'Name': 'Charlie', 'Num': {12}}, {'Name': 'Anna', 'Num': {17, 20, 21}}]
Line by line {'name': 'Jen', 'numbers': {3, 6, 8, 9, 13, 14}}
name Dicc: {'Name': 'Jen', 'Num': {17, 20, 21}}
xxxxxxxxxx NUMPLAYER before APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}, {'Name': 'Charlie', 'Num': {12}}, {'Name': 'Anna', 'Num': {17, 20, 21}}]
******number Dicc: {'Name': 'Jen', 'Num': set()}
///////// NUMPLAYER after APPEND inside FOR [1000, {'Name': 'Rolf', 'Num': {12}}, {'Name': 'Charlie', 'Num': {12}}, {'Name': 'Anna', 'Num': {17, 20, 21}}, {'Name': 'Jen', 'Num': set()}]
Related
The user selects the amount value and quantity of the product. After that, a list is taken from the database, which is filtered by amount. But they get absolutely all the values. I would like to somehow be able to dynamically change the limit.
Is it possible to dynamically limit the number of lines for each denomination through the database, or do it directly with Python tools?
async def get_cards_info(self, cards_amount: list):
sql = select(GiftCard.id, GiftCard.card_number, GiftCard.card_amount, GiftCard.card_price).where(
GiftCard.card_amount.in_(cards_amount))
result = (await self.session.execute(sql)).all()
return result
The function outputs the following data:
[{'id': 4, 'number': '825df05d-8186-4c81-bab6-8374c134c8d1', 'amount': 50, 'price': 70},
{'id': 6, 'number': '1d1d57b4-b032-47cc-8656-edf7cf110d99', 'amount': 50, 'price': 70},
{'id': 14, 'number': '3c966ee9-ebae-4f5b-baea-afb6af82adba', 'amount': 50, 'price': 70},
{'id': 17, 'number': 'c17a151d-d624-4976-8098-8112d0c16590', 'amount': 20, 'price': 30},
{'id': 18, 'number': '1965defd-91b7-4c7e-b41b-3f79debfaad8', 'amount': 20, 'price': 30},
{'id': 19, 'number': '19834dda-fb73-4890-aad2-8d35560f8c2b', 'amount': 20, 'price': 30},
{'id': 20, 'number': 'ec8fa090-06f9-4fbe-8f82-b54b6ffdc756', 'amount': 50, 'price': 70}]
Variable tsv_data has the following structure:
[
{'id':1,'name':'bob','type':'blue','size':2},
{'id':2,'name':'bob','type':'blue','size':3},
{'id':3,'name':'bob','type':'blue','size':4},
{'id':4,'name':'bob','type':'red','size':2},
{'id':5,'name':'sarah','type':'blue','size':2},
{'id':6,'name':'sarah','type':'blue','size':3},
{'id':7,'name':'sarah','type':'green','size':2},
{'id':8,'name':'jack','type':'blue','size':5},
]
Which I would like to restructure into:
[
{'name':'bob', 'children':[
{'name':'blue','children':[
{'id':1, 'size':2},
{'id':2, 'size':3},
{'id':3, 'size':4}
]},
{'name':'red','children':[
{'id':4, 'size':2}
]}
]},
{'name':'sarah', 'children':[
{'name':'blue','children':[
{'id':5, 'size':2},
{'id':6, 'size':3},
]},
{'name':'green','children':[
{'id':7, 'size':2}
]}
]},
{'name':'jack', 'children':[
{'name':'blue', 'children':[
{'id':8, 'size':5}
]}
]}
]
What is obstructing my progress is not knowing how many items will be in the children list for each major category. In a similar vein, we also don't know which categories will be present. It could be blue or green or red -- all three or in any combination (like only red and green or only green).
Question
How might we devise a fool-proof way to compile the basic list of list contained in tsv_data into a multi-tier hierarchical data structure as above?
Given your major categories as a list:
categories = ['name', 'type']
You can first transform the input data into a nested dict of lists so that it's easier and more efficient to access children by keys than your desired output format, a nested list of dicts:
tree = {}
for record in tsv_data:
node = tree
for category in categories[:-1]:
node = node.setdefault(record.pop(category), {})
node.setdefault(record.pop(categories[-1]), []).append(record)
tree would become:
{'bob': {'blue': [{'id': 1, 'size': 2}, {'id': 2, 'size': 3}, {'id': 3, 'size': 4}], 'red': [{'id': 4, 'size': 2}]}, 'sarah': {'blue': [{'id': 5, 'size': 2}, {'id': 6, 'size': 3}], 'green': [{'id': 7, 'size': 2}]}, 'jack': {'blue': [{'id': 8, 'size': 5}]}}
You can then transform the nested dict to your desired output structure with a recursive function:
def transform(node):
if isinstance(node, dict):
return [
{'name': name, 'children': transform(child)}
for name, child in node.items()
]
return node
so that transform(tree) would return:
[{'name': 'bob', 'children': [{'name': 'blue', 'children': [{'id': 1, 'size': 2}, {'id': 2, 'size': 3}, {'id': 3, 'size': 4}]}, {'name': 'red', 'children': [{'id': 4, 'size': 2}]}]}, {'name': 'sarah', 'children': [{'name': 'blue', 'children': [{'id': 5, 'size': 2}, {'id': 6, 'size': 3}]}, {'name': 'green', 'children': [{'id': 7, 'size': 2}]}]}, {'name': 'jack', 'children': [{'name': 'blue', 'children': [{'id': 8, 'size': 5}]}]}]
Demo: https://replit.com/#blhsing/NotableCourageousTranslations
The example code -
innerdict = {}
outerdict = {}
for line in range(1, 10, 2):
for j in range(1, 10, 2):
line_tuple = ("Item" + str( line ), int( line ))
key = line_tuple[1]
if line ==j:
outerdict[key] = dict( innerdict )
outerdict[key] = {'Name': '{0}'.format( "item"+str(j) ), 'Price': '{0}'.format( j )}
print(outerdict)
The ouput comes out like this-
{1: {'Name': 'item1', 'Price': '1'}, 3: {'Name': 'item3', 'Price': '3'}, 5: {'Name': 'item5', 'Price': '5'}, 7: {'Name': 'item7', 'Price': '7'}, 9: {'Name': 'item9', 'Price': '9'}}
The above output is achievable since it is conventional. I found a lot of online suggestions regarding nested dictionary comprehension.
But I want the output to come out like below-
{{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'}, {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}}
Thanks in advance!
This is not possible, as the dict objects are not hashable.
{{1:2}} would mean putting a dict {1:2} into a set, which is not possible because of the un-hashability of the objects mentioned above. Better put them in a list:
[{1:2}, {2:3}]
What you want is something like a list of dictionaries. And this {{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'}, {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}} is invalid as dictionary is considered to be a key-value pair and there is no key in this.
It can be checked by assigning the above to a variable and then checking its type.
d = {{'Name': 'item1', 'Price': '1'}, {'Name': 'item3', 'Price': '3'}, {'Name': 'item5', 'Price': '5'}, {'Name': 'item7', 'Price': '7'}, {'Name': 'item9', 'Price': '9'}}
print(type(d))
It will result in an error saying it's unhashable.
Here is the simplified version of the problem ;)
Given following list,
my_list = [{'name': 'apple', 'type': 'fruit'},
{'name': 'orange', 'type': 'fruit'},
{'name': 'mango', 'type': 'fruit'},
{'name': 'tomato', 'type': 'vegetable'},
{'name': 'potato', 'type': 'vegetable'},
{'name': 'leek', 'type': 'vegetable'}]
How to pick only two items from the list for a particular type to achieve following?
filtered = [{'name': 'apple', 'type': 'fruit'},
{'name': 'orange', 'type': 'fruit'},
{'name': 'tomato', 'type': 'vegetable'},
{'name': 'leek', 'type': 'vegetable'}]
You can use itertools.groupby to group the elements of your list based on type and the grab only the first 2 elements from each group.
>>> from itertools import groupby
>>> f = lambda k: k['type']
>>> n = 2
>>> res = [grp for _,grps in groupby(sorted(my_list, key=f), f) for grp in list(grps)[:n]]
>>> pprint(res)
[{'name': 'apple', 'type': 'fruit'},
{'name': 'orange', 'type': 'fruit'},
{'name': 'tomato', 'type': 'vegetable'},
{'name': 'potato', 'type': 'vegetable'}]
you can groupby then pick the first 2:
from itertools import groupby
a = [list(j)[:2] for i, j in groupby(my_list, key = lambda x: x['type'])]
print(a)
[[{'name': 'apple', 'type': 'fruit'}, {'name': 'orange', 'type': 'fruit'}],
[{'name': 'tomato', 'type': 'vegetable'},
{'name': 'potato', 'type': 'vegetable'}]]
sum(a,[])
Out[299]:
[{'name': 'apple', 'type': 'fruit'},
{'name': 'orange', 'type': 'fruit'},
{'name': 'tomato', 'type': 'vegetable'},
{'name': 'potato', 'type': 'vegetable'}]
If I have the following tuple...:
("Year-7 [{'Name': 'Barry', 'Age': 11}, {'Name': 'Larry', 'Age': 11}]",
"Year-8 [{'Name': 'Harry', 'Age': 11}, {'Name': 'Parry', 'Age': 11}]",
"Year-9 [{'Name': 'Sally', 'Age': 11}, {'Name': 'Garry', 'Age': 11}]")
How do I split this up into the following tuples?
("Year-7", "Year-8, "Year-9")
("[{'Name': 'Barry', 'Age': 11}, {'Name': 'Larry', 'Age': 11}]", "[{'Name': 'Harry', 'Age': 11}, {'Name': 'Parry', 'Age': 11}]", "[{'Name': 'Sally', 'Age': 11}, {'Name': 'Garry', 'Age': 11}]")
Thanks in advance,
Jack
.................
t = ("Year-7 [{'Name': 'Barry', 'Age': 11}, {'Name': 'Larry', 'Age': 11}]",
"Year-8 [{'Name': 'Harry', 'Age': 11}, {'Name': 'Parry', 'Age': 11}]",
"Year-9 [{'Name': 'Sally', 'Age': 11}, {'Name': 'Garry', 'Age': 11}]")
tuple([k[7:] for k in list(t)])
Did you also want:
tuple([k[:6] for k in list(t)])