Starting form a list:
user1 = ['alternative', 'rock', 'pop']
I can populate a dictionary with the number of appearences of each item.
u1={}
for tag in user1:
u1[tag]=1
print u1
and get: {'alternative': 1, 'pop': 1, 'rock': 1}
likewise, for:
user2 = ['indie', 'rock', 'chamber pop']
the same:
u2={}
for tag in user2:
u2[tag]=1
print u2
and get: {'indie': 1, 'chamber pop': 1, 'rock': 1}, and so on.
but lets say I want to populate this dict in the same fashion:
users = {
u1:{},
u2:{},
u3:{},
...
...
}
how can I do it?
Let's say you have users and lists already stored to a dictionary. Then you could iterate over all key value pairs within dictionary comprehension and use Counter to convert the list to dict with counts:
from collections import Counter
users = {
'u1': ['alternative', 'rock', 'pop'],
'u2': ['indie', 'rock', 'chamber pop'],
'u3': ['indie', 'rock', 'alternative', 'rock']
}
res = {k: Counter(v) for k, v in users.items()}
print(res)
Output:
{'u1': Counter({'alternative': 1, 'pop': 1, 'rock': 1}),
'u3': Counter({'rock': 2, 'indie': 1, 'alternative': 1}),
'u2': Counter({'indie': 1, 'chamber pop': 1, 'rock': 1})}
To break above a bit users.items() returns an iterable of (key, value) tuples:
>>> list(users.items())
[('u2', ['indie', 'rock', 'chamber pop']), ('u1', ['alternative', 'rock', 'pop']), ('u3', ['indie', 'rock', 'alternative', 'rock'])]
Then dict comprehension turns the list to dict containing the counts:
>>> Counter(['indie', 'rock', 'chamber pop'])
Counter({'rock': 1, 'indie': 1, 'chamber pop': 1})
Finally for each the user name and resulting Counter are added the to the result dict.
Counter is a good option. But according to this question we can use more simple option. Check this out.
users = {
'u1': ['alternative', 'rock', 'pop'],
'u2': ['indie', 'rock', 'chamber pop'],
}
res = {}
for user in users.items(): # return each key:value pair as tuple
res[user[0]] = {} # first element of tuple used as key in `res` for each list
for tag in user[1]: # return each element of list
res[user[0]][tag] = 1 # assign value as 1 of each element.
print res
Output:
{'u1': {'alternative': 1, 'pop': 1, 'rock': 1}, 'u2': {'indie': 1, 'chamber pop': 1, 'rock': 1}}
Related
I have the following nested dictionary:
Student_dict = {'A123':
{'Student_Name': 'Lisa Simpson',
'Class_Year': 1,
'CGPA': 3.98},
'A125':
{'Student_Name': 'Bart Simpson',
'Class_Year': 3,
'CGPA': 2.51},
'A234': {'Student_Name': 'Milhouse Houten',
'Class_Year': 3,
'CGPA': 3.62}}
And I have to add the key "Honors" within each of the dictionaries and associate the value "Yes" if the CGPA value of the student is higher than 3.7 and "No" otherwise, using loops and if statement.
The expected output is the following:
Student_dict = {
'A123': {
'Student_Name': 'Lisa Simpson',
'Class_Year': 1,
'CGPA': 3.98,
'Honors': 'Yes'
},
'A125': {
'Student_Name': 'Bart Simpson',
'Class_Year': 3,
'CGPA': 2.51,
'Honors': 'No'
},
'A234': {
'Student_Name': 'Milhouse Houten',
'Class_Year': 3,
'CGPA': 3.62,
'Honors': 'No'}}
I've tried various things, but my problem is assessing the different student ids (A123, A125, A234) to create my loop.
Could someone help me please?
Thank you in advance!
You may refer to the inner dictionaries using .values(), this way, you do not need to know the explicit studentpeople ids.
for value in Student_dictPeople.values():
if value['CGPA']value['Age'] > 3.7018:
value['Honors']value['Adult'] = "Yes"
else:
value['Honors']value['Adult'] = "No"
print(Student_dict)
Output:
{'A123': {'Student_Name': 'Lisa Simpson', 'Class_Year': 1, 'CGPA': 3.98, 'Honors': 'Yes'}, 'A125': {'Student_Name': 'Bart Simpson', 'Class_Year': 3, 'CGPA': 2.51, 'Honors': 'No'}, 'A234': {'Student_Name': 'Milhouse Houten', 'Class_Year': 3, 'CGPA': 3.62, 'Honors': 'No'}}
Looping through dict in python work like this :
dict = {'A123' : {'Student_Name' : 'Lisa'} }
# Access ID with for and subcategory using this id
for id in dict:
name = dict[id]['Student_Name']
# Assigning new value :
value = 3
for id in dict:
dict[id]['CGPA'] = value
I'll do it that way
def treat_dict(input):
for id in input:
if input[id]['CGPA'] >= 3.7:
input[id]['Honors'] = 'Yes' # Add new value
else:
input[id]['Honors'] = 'No' # Add new value
return input
In a more compressed way:
def treat_dict(input):
for id in input:
input[id]['Honors'] = 'Yes' if input[id]['CGPA'] >= 3.7 else 'No'
return input
Edit : didn't see that someone replied but letting it...
I have a list of names:
list = ['Ginger', 'Willow', 'Scout', 'Roscoe', 'Bear', 'Kobe', 'Baxter', 'Zara', 'Fiona', 'Milo', 'Oakley', 'Dakota', 'Prince', 'Bruno', 'Panda', 'Dexter', 'Ziggy', 'Roscoe', 'Lucy', 'Boomer', 'Fiona', 'Ella', 'Emma', 'Oakley']
Using this list, I've created the following dictionary:
listA = {"G": "Ginger", "W": "Willow", "S": "Scout", "R": ["Roscoe", "Roscoe"], "B": ["Bear", "Baxter", "Bruno", "Boomer"], "K": "Kobe", "Z": ["Zara", "Ziggy"], "F": ["Fiona", "Fiona"], "M": "Milo", "O": ["Oakley", "Oakley"], "D": ["Dakota", "Dexter"], "P": ["Prince", "Panda"], "L": "Lucy", "E": ["Ella", "Emma"]}
Printing the keys from the dictionary:
for key in listA.keys():
print(key)
I get:
G
W
S
R
B
K
Z
F
M
O
D
P
L
E
How can I get the number of times that each name appears in the list?
You don't need listA; collections.Counter does exactly what you're looking for.
import collections
data = ['Ginger', 'Willow', 'Scout', 'Roscoe', 'Bear', 'Kobe', 'Baxter', 'Zara', 'Fiona', 'Milo', 'Oakley', 'Dakota', 'Prince', 'Bruno', 'Panda', 'Dexter', 'Ziggy', 'Roscoe', 'Lucy', 'Boomer', 'Fiona', 'Ella', 'Emma', 'Oakley']
counter = collections.Counter(data)
print(counter) # Prints counter object.
counter_as_dict = dict(counter) # Can be transformed into a dictionary using dict().
print(counter_as_dict.keys()) # Prints names in dictionary.
I have this json with different levels:
[{'A': 1, 'B': 2, 'CA': {'CA1': '3', 'CA23': '4'}},
{'A': 1, 'B': {'CA1': '3'}, 'CA': {'CA1': '3', 'CA23': '4'}}]
And I want to get only the values for each row using list comprehension:
The expected result is:
[[1, 2, '3', '4'], [1, '3', '3', '4']]
Without using list comprehension this code work:
values = []
for row in json:
rows = []
for item in row.items():
if str(row[item[0]]).startswith("{"):
temp = row[item[0]].values()
else:
temp = [row[item[0]]]
rows.extend(temp)
values.append(rows)
Some ideas?
Here's a way to do it that cheats a little by using an auxiliary helper function to flatten the nested dictionary objects comprising each "row" of your data-structure.
import json # For pretty-printing data and results.
from collections.abc import MutableMapping
def flatten(nested):
''' Yield values from nested dictionary data structure. '''
for value in nested.values():
if isinstance(value, MutableMapping): # Nested?
yield from flatten(value)
else:
yield value
json_values = [{'A': 1, 'B': 2, 'CA': {'CA1': '3', 'CA23': '4'}},
{'A': 1, 'B': {'CA1': '3'}, 'CA': {'CA1': '3', 'CA23': '4'}}]
print('Before:')
print(json.dumps(json_values, indent=4))
# Here's the list comprehension.
result = [list(flatten(nested)) for nested in json_values]
print()
print('After:')
print(json.dumps(result, indent=4))
Output:
Before:
[
{
"A": 1,
"B": 2,
"CA": {
"CA1": "3",
"CA23": "4"
}
},
{
"A": 1,
"B": {
"CA1": "3"
},
"CA": {
"CA1": "3",
"CA23": "4"
}
}
]
After:
[
[
1,
2,
"3",
"4"
],
[
1,
"3",
"3",
"4"
]
]
Can anyone help me with this function? I have no clue to write the code and what I wrote in the function body is wrong.
def get_quantities(table_to_foods: Dict[str, List[str]]) -> Dict[str, int]:
"""The table_to_foods dict has table names as keys (e.g., 't1', 't2', and
so on) and each value is a list of foods ordered for that table.
Return a dictionary where each key is a food from table_to_foods and each
value is the quantity of that food that was ordered.
>>> get_quantities({'t1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'],
't3': ['Steak pie', 'Poutine', 'Vegetarian stew'], 't4': ['Steak pie', 'Steak pie']})
{'Vegetarian stew': 3, 'Poutine': 2, 'Steak pie': 3}
"""
food_to_quantity = {}
for t in table_to_foods:
for i in table_to_foods[t]:
if i in table_to_foods[t]:
food_to_quantity[i] = food_to_quantity[i] + 1
return food_to_quantity
Just another way of doing in case you like using itertools.chain and collections.Counter:
from itertools import chain
from collections import Counter
dict(Counter(chain.from_iterable(foods.values())))
#or Simply
dict(Counter(chain(*foods.values())))
#Output:
#{'apple': 3, 'banana': 4, 'grapes': 1, 'orange': 1}
A common way to count items without a library is to use python get() function
foods = {
't1': ['banana', 'apple', 'banana'],
't2': ['orange', 'apple', 'banana'],
't3': ['apple', 'grapes', 'banana']
}
def get_quantities(foodLists):
totals = {}
for foodList in foodLists.values():
for food in foodList:
totals[food] = totals.get(food, 0) + 1
return totals
print(get_quantities(foods))
Which prints:
{'banana': 4, 'apple': 3, 'orange': 1, 'grapes': 1}
Use Counters
from collections import Counter
def get_quantities(table_to_foods: Dict[str, List[str]]) -> Dict[str, int]:
return dict(Counter(x for v in table_to_foods.values() for x in v))
You probably don't have to make a dict from the Counter (Counter is a subclass of dict), but I do it here so your types are identical
Try this:
def get_quantities(table_to_foods):
food_to_quantity = {}
for table in table_to_foods.values():
for food in table:
food_to_quantity[food] = food_to_quantity.get(food, 0) + 1
return food_to_quantity
You can use .values() to get the values in a dictionary and then iterate through each item. If the food is in the dictionary then add 1 to it's value and if not then add the food as a new item in the dictionary.
get_quantities({
't1': ['Vegetarian stew', 'Poutine', 'Vegetarian stew'],
't2': ['Steak pie', 'Poutine', 'Vegetarian stew'],
't3': ['Steak pie', 'Steak pie']
})
should output the following if printed:
{'Poutine': 2, 'Steak pie': 3, 'Vegetarian stew': 3}
More about dictionaries:
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
I have a list of dictionary as follows.
mylist = [ {"0": ["code1", "code5"], "1" ["code8", "code7", "code2"]},
{"1": ["code2", "code3"], "2" ["code4", "code5", "code7"], "3": ["code1", "code10"]},
{"0": ["code8", "code5", "code1"], "2" ["code7", "code5", "code2"]} ]
Now, I want to calculate the codes count for each key in the dictionary. For example "0": ["code1", "code5"] and "0": ["code8", "code5"] should give: mydict_for_0 = {"code1": 1, "code5": 2, "code8": 1}
So, for the above mylist the output should be;
mydict_for_0 = {"code1": 2, "code5": 2, "code8": 1}
mydict_for_1 = {"code2": 2, "code3": 1, "code7": 1, "code8": 1}
mydict_for_2 = {"code4": 1, "code5": 2, "code7": 2, {"code2": 1}
mydict_for_3 = {"code1": 1, "code10": 1}
Please help me to do this using python!
Try with defaultdict, Counter from collections module, find all same key's value list, extend them into one list, save into a defaultdict(list):
from collections import defaultdict, Counter
new_dict = defaultdict(list)
for e in mylist:
for key,value in e.items():
new_dict[key].extend(value)
new_dict will be:
defaultdict(list,
{'0': ['code1', 'code5', 'code8', 'code5', 'code1'],
'1': ['code8', 'code7', 'code2', 'code2', 'code3'],
'2': ['code4', 'code5', 'code7', 'code7', 'code5', 'code2'],
'3': ['code1', 'code10']})
After that, loop all items to pass the values list into Counter, to count the occurrences of list:
result = {}
for key,value in new_dict.items():
result['mydict_for_'+key] = dict(Counter(value))
result will be:
{'mydict_for_0': {'code1': 2, 'code5': 2, 'code8': 1},
'mydict_for_1': {'code2': 2, 'code3': 1, 'code7': 1, 'code8': 1},
'mydict_for_2': {'code2': 1, 'code4': 1, 'code5': 2, 'code7': 2},
'mydict_for_3': {'code1': 1, 'code10': 1}}
This might be the solution
final_result = []
for i in mylist:
current_list = mylist[i]
d = {}
for key in current_list:
try:
d[m]+=1
except KeyError as e:
d.update({m: 1})
final_result.append(d)
for i in final_result:
print(i)