groups = ['A','B','C']
ranges = [1,2,3,4,5,6,7,8,9]
my_dict = {}
for g in groups:
my_dict[g] = ???
The result (my_dict) should be as follows:
{'A': array([1, 2, 3], dtype=int64), 'B': array([4,5,6], dtype=int64)), 'C': array([7,8,9], dtype=int64)}
First I would turn your ranges in to properly sized chunks:
>>> ranges = zip(*[iter(ranges)]*len(groups))
>>> print(ranges)
[(1, 2, 3), (4, 5, 6), (7, 8, 9)]
This will create chunks of len(groups) items which you can then feed to zip() in the second part.
Then create the dictionary, using a dictionary comprehension and zip().
>>> from numpy import array
>>> my_dict = {g: array(r) for g, r in zip(groups, ranges)}
>>> print(my_dict)
{'A': array([1, 2, 3]), 'C': array([7, 8, 9]), 'B': array([4, 5, 6])}
>>> import itertools
>>>
>>> groups = ['A','B','C']
>>> ranges = [1,2,3,4,5,6,7,8,9]
>>> dict(zip(groups,
... (list(itertools.islice(it, 3)) for it in [iter(ranges)]*3)))
{'A': [1, 2, 3], 'C': [7, 8, 9], 'B': [4, 5, 6]}
Related
I have list of identical dictionaries:
my_list = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}]
I need to get something like this:
a = [1, 4, 7]
b = [2, 5, 8]
c = [3, 6, 9]
I know how to do in using for .. in .., but is there way to do it without looping?
If i do
a, b, c = zip(*my_list)
i`m getting
a = ('a', 'a', 'a')
b = ('b', 'b', 'b')
c = ('c', 'c', 'c')
Any solution?
You need to extract all the values in my_list.You could try:
my_list = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}]
a, b, c = zip(*map(lambda d: d.values(), my_list))
print(a, b, c)
# (1, 4, 7) (2, 5, 8) (3, 6, 9)
Pointed out by #Alexandre,This work only when the dict is ordered.If you couldn't make sure the order, consider the answer of yatu.
You will have to loop to obtain the values from the inner dictionaries. Probably the most appropriate structure would be to have a dictionary, mapping the actual letter and a list of values. Assigning to different variables is usually not the best idea, as it will only work with the fixed amount of variables.
You can iterate over the inner dictionaries, and append to a defaultdict as:
from collections import defaultdict
out = defaultdict(list)
for d in my_list:
for k,v in d.items():
out[k].append(v)
print(out)
#defaultdict(list, {'a': [1, 4, 7], 'b': [2, 5, 8], 'c': [3, 6, 9]})
Pandas DataFrame has just a factory method for this, so if you already have it as a dependency or if the input data is large enough:
import pandas as pd
my_list = ...
df = pd.DataFrame.from_rows(my_list)
a = list(df['a']) # df['a'] is a pandas Series, essentially a wrapped C array
b = list(df['b'])
c = list(df['c'])
Please find the code below. I believe that the version with a loop is much easier to read.
my_list = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9}]
# we assume that all dictionaries have the sames keys
a, b, c = map(list, map(lambda k: map(lambda d: d[k], my_list), my_list[0]))
print(a,b,c)
How do I multiply the values of this dictionary by 2?
d = {'a': (1,2), 'y': (2,4), 'z': (10,3)}
I get this
for i in d:
print(d[i]*2)
[1, 2, 1, 2]
[2, 4, 2, 4]
[10, 3, 10, 3]
but I want to achieve:
[2,4]
[4,8]
[20,6]
You're attempting to multiply a tuple which is resulting in the duplication of the values in your tuple. Instead, to algebraically interact with your tuples, you must do so one value at a time.
for i in d:
print(d[i][0]*2, d[i][1]*2)
You need to iterate through dictionary values and multiply each element by 2, not tuples * 2:
d = {'a': (1,2), 'y': (2,4), 'z': (10,3)}
for x in d.values():
print([y*2 for y in x])
# [2, 4]
# [4, 8]
# [20, 6]
What you are doing is:
>>> tupl = (1, 2)
>>> tupl * 2
(1, 2, 1, 2)
Here you need to do list comprehension
d = {'a': (1,2), 'y': (2,4), 'z': (10,3)}
for k in d.keys():
d[k] = [2*x for x in d[k]]
print(d)
{'a': [2, 4], 'y': [4, 8], 'z': [20, 6]}
I would like to convert my list of lists to list of dictionaries. Values of first list should be my keys and remaining all should be treated as values.
For example:
[['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]
should convert to
[{'a':[1,4,7]}, {'b': [2,5,8]},{'b': [3,6,9]}]
I found this but it did n't help for me..
Any help would be greatly appreciated. Thanks
Use zip to transpose your array into [('a', 1, 4, 7), ...]; pop off the first element as key, listify the rest as value.
arr = [['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]
[{ e[0]: list(e[1:])} for e in zip(*arr)]
# => [{'a': [1, 4, 7]}, {'b': [2, 5, 8]}, {'c': [3, 6, 9]}]
Using a list comprehension with sequence unpacking:
L = [['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]
res = [{names: nums} for names, *nums in zip(*L)]
print(res)
[{'a': [1, 4, 7]}, {'b': [2, 5, 8]}, {'c': [3, 6, 9]}]
a=[['a','b','c'],[1,2,3],[4,5,6],[7,8,9]]
dictionary_values=[dict([(a[0][i],list(zip(*a[1:])[i])) for i in range (len(a)-1)])]
output:
[{'a': [1, 4, 7], 'b': [2, 5, 8], 'c': [3, 6, 9]}]
I have this code:
import sympy
import numpy as np
arr = [np.array([ 1, 2, 3, 4]), np.array([ 5, 6, 7, 8])]
a,b = sympy.symbols('a b')
var = [a,b]
new_dict = dict(zip(str(var), arr))
And my output is:
print(new_dict)
{'[': array([1, 2, 3, 4]), 'a': array([5, 6, 7, 8])}
instead of:
{'a': array([1, 2, 3, 4]), 'b': array([5, 6, 7, 8])}
How can I fix that?
When you send a list to str(), it gives you the representation of that list as a string, which includes brackets and commas. You want the string representation of each value in that list:
new_dict = dict(zip(map(str, var), arr))
Or, better yet, since var seems to hold strings anyway:
new_dict = dict(zip(var, arr))
I have a Python dictionary of lists like this one:
d = {'A': [(4, 4, 3), [1, 2, 3, 4, 5]],
'B': [(2, 1, 2), [5, 4, 3, 2, 1]],
'C': [(4, 1, 1), [2, 4, 1, 2, 4]]}
I need to create a formula that accesses the elements of the dictionary and, for every value [t, l]:
Calculates the mean of t (let's call this m);
Takes a random sample s, with replacement and of length len(t), from l;
Compares m with the mean of s - True if m is greater than the mean of s, False otherwise;
Repeats this process 10,000 times
Returns the percentage of times m is greater than the mean of s.
The output should look like:
In [16]: test(d)
Out[16]: {'A': 0.5, 'B': 0.9, 'C': 0.4}
I think I'm not that far from an answer, this is what I have tried:
def test(dict):
def mean_diff(dict):
for k, (v0, v1) in dict.iteritems():
m = np.mean(v0) > (np.mean(npr.choice(v1, size=(1, len(v0)), replace=True)))
return ({k: m})
for k, (v0, v1) in dict.iteritems():
bootstrap = np.array([means_diff(dict) for _ in range(10000)])
rank = float(np.sum(bootstrap))/10000
return ({k: rank})
However, I got:
RuntimeError: maximum recursion depth exceeded while calling a Python object
I'd use a list comprehension that essentially selects a random value and compares it to the mean. This will produce a list of True/False. If you take the mean of that, it will be averaging a list of 1's and 0's, so it will give you the aggregate probability.
import numpy as np
d = {'A': [(4, 4, 3), [1, 2, 3, 4, 5]],
'B': [(2, 1, 2), [5, 4, 3, 2, 1]],
'C': [(4, 1, 1), [2, 4, 1, 2, 4]]}
def makeRanks(d):
rankDict = {}
for key in d:
tup = d[key][0]
mean = np.mean(tup)
l = d[key][1]
rank = np.mean([mean > np.mean(np.random.choice(l,len(tup))) for _ in range(10000)])
rankDict[key] = rank
return rankDict
Testing
>>> makeRanks(d)
{'C': 0.15529999999999999, 'A': 0.72130000000000005, 'B': 0.031899999999999998}