Splitting tuple into segments - python-3.x

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

Related

Dictionaries appended and updating create clones

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

Comparing dictionary list. TypeError: tuple indices must be integers or slices, not str

I am trying to compare two sets of data (file1,file2) in a dictionary format. When comparing using example 1 (see bellow), the code works but when I add more data (example 2) I get an error as tuple indices must be integer or slices. I'm struggling to understand this, since I'm comparing two sets of dictionaries and not a list to use an integer to compare using integers in the index rather than the name of key in the dictionary.
#Dict list example 1: with this example, it works
file1= {'name': 'Phill', 'age': 42}
file2= {'name': 'Phill', 'age': 22}
#Dict list example 2: with this example, it doesn't work
file1= {'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}
file2= {'name': 'Phill', 'age': 22},{'name': 'Phill', 'age': 52}
#Function with two args
def diffValue (file1,file2) :
for newAge in file1,file2 :
if file1 [ 'age' ] == file2 [ 'age' ] :
# if no difference found in both files within the age field
print ( "No difference found" )
else :
# the age is different. return values name,age where ever there is a difference from file1 only
return newAge
Expected results:
Return {'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}
I think you meant to do something like this:
file1 = {'name': 'Phill', 'age': 42}, {'name': 'Phill', 'age': 22}
file2 = {'name': 'Phill', 'age': 22}, {'name': 'Phill', 'age': 52}
def diff_value(f1, f2):
# Create a list to store the differences
diffs = []
# Iterate for every element in parallel
for v1, v2 in zip(f1, f2):
if v1['age'] == v2['age']:
# If no difference found in both files within the age field
print('No difference found')
else:
# The age is different, append v1 to `diffs`
diffs.append(v1)
return diffs
print(diff_value(file1, file2))
# Output: [{'name': 'Phill', 'age': 42}, {'name': 'Phill', 'age': 22}]
>>> file1= {'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}
>>> file1
({'name': 'Phill', 'age': 42}, {'name': 'Phill', 'age': 22})
>>> type(file1)
<class 'tuple'>
file1 is tuple that is why it gives an error
one way to make it work with your function is:
def diffValue (file1,file2) :
for newAge in file1,file2 :
if file1 [ 'age' ] == file2 [ 'age' ] :
# if no difference found in both files within the age field
print ( "No difference found" )
else :
# the age is different. return values name,age where ever there is a difference from file1 only
return newAge
file1= [{'name': 'Phill', 'age': 42},{'name': 'Phill', 'age': 22}]
file2= [{'name': 'Phill', 'age': 22},{'name': 'Phill', 'age': 52}]
a=""
for i in range(len(file1)):
a+=str(diffValue(file1[i],file2[i]))+","
a=a[:-1]
print(a)

How can I enter a dictionary inside an another empty dictionary?

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.

Python list of dictionaries search with multiple input

Sorry for such a stupid question but im on deadend right now (1st time using python), how do i search Python list of dictionaries with multiple
attribute ?
My current code is only can search by 1 attribute.
people = [{'name': 'Alex', 'age': '19',
'grade': 80},
{'name': 'Brian', 'age': '17', 'grade':
90},
{'name': 'Junior', 'age': '17', 'grade':
90},
{'name': 'Zoey', 'age': '19', 'grade':
95},
{'name': 'joe', 'age': '18', 'grade':
90}]
entry=input("Check the name you want to search the grade :")
list(filter(lambda person: person['name'] == entry, people))
I want it to search by multitple attribute, so if i input either '17' or 90, the expected output is
[{'name': 'Brian', 'age': '17', 'grade': 90},
{'name': 'Junior', 'age': '17', 'grade': 90}]
You could just use two conditions connected by an or (while taking measures not to compare strings with numbers):
list(filter(lambda person: str(person['grade']) == entry or str(person['grade']) == entry, people))
At some point, a comprehension will be more readable:
[p for p in people if str(person['grade']) == entry or str(p['grade']) == entry]
And if you want to add more search keys, you can further DRY this out, using any:
keys = ('name', 'grade', 'age')
filtered = [p for p in people if any(str(p[k]) == entry for k in keys)]

Pick two items from a list based on a condition

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

Resources