I have a list of dictionaries with the same key names, I want to consolidate the dictionaries into one dictionary with averaged values only in number-based values:
[{'a': 3, 'b': 'm', 'c': 7},
{'a': 1.0, 'b': 'm', 'c': 2},
{'a': 5, 'b': 'm', 'c': 4.0}]
into an averaged dictionary:
[{'a': 3, 'b': 'm', 'c': 4}]
If you can assume you have at least one dict in the list and all the dicts have all the keys you can do:
import numbers
dicts =[{'a': 3, 'b': 'm', 'c': 7},
{'a': 1.0, 'b': 'm', 'c': 2},
{'a': 5, 'b': 'm', 'c': 4.0}]
avg_dict = {}
for key in dicts[0]:
avg_dict[key] = sum([d[key] for d in dicts])/len(dicts) if isinstance(dicts[0][key], numbers.Number) else dicts[0][key]
Maybe not the most pythonic way, but it will do the job:
lst = [{'a': 3, 'b': 'm', 'c': 7},
{'a': 1.0, 'b': 'm', 'c': 2},
{'a': 5, 'b': 'm', 'c': 4.0}]
result = {}
for item in lst:
for j in item:
if type(item[j]) == str:
result[j] = item[j]
elif j in result:
result[j] += item[j]
else:
result[j] = item[j]
for i in result:
if type(result[i]) != str:
result[i] = int(result[i] / len(lst))
print(result)
Related
please help with code to print value of key c by comparing key value of a and b
the output should be 29
int a = 3;
int b = 6;
List nums = [
{'a': 1, 'b': 6, 'c': 9},
{'a': 1, 'b': 7, 'c': 10},
{'a': 3, 'b': 8, 'c': 19},
{'a': 3, 'b': 6, 'c': 29},
{'a': 2, 'b': 7, 'c': 39},
{'a': 2, 'b': 8, 'c': 49},
];
As per https://api.dart.dev/stable/2.16.2/dart-core/Iterable/where.html
void main() {
int a = 3;
int b = 6;
List nums = [
{'a': 1, 'b': 6, 'c': 9},
{'a': 1, 'b': 7, 'c': 10},
{'a': 3, 'b': 8, 'c': 19},
{'a': 3, 'b': 6, 'c': 29},
{'a': 2, 'b': 7, 'c': 39},
{'a': 2, 'b': 8, 'c': 49},
];
print(nums.where((m) => m['a'] == a && m['b'] == b));
print(nums.where((m) => m['a'] == a && m['b'] == b).elementAt(0)['c']);
}
the output will be
({a: 3, b: 6, c: 29})
29
The following code will output 29.
main(){
int a = 3;
int b = 6;
List nums = [
{'a': 1, 'b': 6, 'c': 9},
{'a': 1, 'b': 7, 'c': 10},
{'a': 3, 'b': 8, 'c': 19},
{'a': 3, 'b': 6, 'c': 29},
{'a': 2, 'b': 7, 'c': 39},
{'a': 2, 'b': 8, 'c': 49},
];
for(var item in nums){
if(item['a'] == a && item['b'] == b){
print(item['c']); // => 29
}
}
}
When I run
print df
the result
A B C D
0 4 8 4-a
7 3 5 3-b
when I select only one column
print df['D']
Nothing showing
print df.info()
Nothing showing
I couldn't understant what is wrong?
I set the data using this code
import pandas as pd
data = {'A': {0: 0, 1: 4, 2: 5, 3: 6, 4: 7, 5: 7, 6: 6},
'B': {0: 's', 1: 's', 2: 's', 3: 's', 4: 's', 5: 's', 6: 's'},
'C': {0: 3, 1: 2, 2: 2, 3: 1, 4: 2, 5: 3, 6: 0},
'D': {0: 'a', 1: 'a', 2: 'a', 3: 'a', 4: 'b', 5: 'b', 6: 'b'}}
df = pd.DataFrame(data)
# Handling column A (first index per value in D)
output_df = df.drop_duplicates(subset='D', keep='first')
# Itering through rows
for index, row in output_df.iterrows():
#Calcultating the counts in B
output_df.loc[index, 'B'] = df[df.D == row.D].B.count()
#Calcultating the sum in C
output_df.loc[index, 'C'] = df[df.D == row.D].C.sum()
#Finally changing values in D by concatenating values in B and D
output_df.loc[:, 'D'] = output_df.B.map(str) + "-" + output_df.D
I have below Python dictionary as source
d1 = {
'a': 1,
'b': 2,
'c': [{'d': 3, 'e': 4, 'un': 'wanted1', 'dont': 'needthis1'},
{'d': 5, 'e': 6, 'un': 'wanted2', 'dont': 'needthis2'}]
'xyz': 'abc',
'zxy': 'cab',
'wva': 'xyw'
}
And I want to copy the values of some specific keys to a different dict to form below target dictionary
d2 = {
'some_attr_1': 1,
'some_attr_x': 2,
'attr_some_z': [{'attr_x': 3, 'attrib': 4},
{'attr_x': 5, 'attrib': 6}]
}
Note:
I am not interested in all the attributes from source
for ex: I don't need keys xyz, zxy, etc
Basically, Want values for some keys in source to be mapped
to different keys in target dictionary.
My current approach is as below to have mapping between source and target dictionary keys.
attr_map1 = {
'some_attr_1': 'a',
'some_attr_x': 'b'
}
attr_map2 = {
'attr_x': 'd',
'attrib': 'e',
}
d2 = dict()
for k, v in attr_map1.items():
d2[k] = d1[v]
l1 = list()
for d_elem in d1['c']:
temp_dict = dict()
for k, v in attr_map2.items():
temp_dict[k] = d_elem[v]
l1.append(temp_dict)
d2['attr_some_z'] = l1
Is there any alternate, better and speedy approach to achieve this?
I am looking for a solution in Python 2.7.
thanks,
You can use recursion:
d1 = {'a': 1, 'b': 2, 'c': [{'d': 3, 'e': 4}, {'d': 5, 'e': 6}]}
def build(d):
return {f't_{a}':b if not isinstance(b, (dict, list)) else
list(map(build, b)) if isinstance(b, list) else build(b) for a, b in d.items()}
print(build(d1))
Output:
{
't_a': 1,
't_b': 2,
't_c': [
{'t_d': 3, 't_e': 4},
{'t_d': 5, 't_e': 6}
]
}
Edit: to run this solution in Python2, replace the f-string with simple concatenation:
d1 = {'a': 1, 'b': 2, 'c': [{'d': 3, 'e': 4}, {'d': 5, 'e': 6}]}
def build(d):
return {'t_'+a:b if not isinstance(b, (dict, list)) else
list(map(build, b)) if isinstance(b, list) else build(b) for a, b in d.items()}
def hashStory():
message = raw_input('Enter Story')
dictionary = {}
for i in message.upper():
dictionary.setdefault(i, 0)
dictionary[i] = dictionary[i] + 1
return dictionary
this code, when used on short strings like 'Hello, how are you', returns this.
{'A': 1, ' ': 3, 'E': 2, 'H': 2, 'L': 2, 'O': 3, 'R': 1, 'U': 1, 'W': 1, 'Y': 1}
But when I want to hash the letters in a story such as this.
RomeoAndJuliet
the punctuation gets in the way. How can I use raw_input to take the words in triple quotes.
Given:
[{'a': '30152', 'b': 'test1', 'c': '10'}, {'a': '30153', 'b': 'test2', 'c': '6'}]
what would I do in Python in order to get the results
['test1', 'test2']
In Java 8 I would do the following:
list.stream().map(Row::getB).collect(Collectors.toList());
One way is to create a maping function that you'll run on every element of your tuple/list of dictionaries
Then you can call function map with your created map function and your list of dictionaries.
def mapB(dict): return dict['b']
myDicts = {'a': '30152', 'b': 'test1', 'c': '10'}, {'a': '30153', 'b': 'test2', 'c': '6'}
list = map(mapB,myDicts)
If you want to create it more dynamicaly, then you can use some map function like this one.
myDicts = {'a': '30152', 'b': 'test1', 'c': '10'}, {'a': '30153', 'b': 'test2', 'c': '6'}
list = map(lambda x: x['b'], dict)