Iterating over maps in List and matching value in Dart - list

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

Related

df.info() doesn't show any information about the dataframe

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

copying multi-level Python dictionaries

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

merge x python dictionaries into 1 with aggregated values

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)

Using Gurobi in Python and adding variables

I am trying to write my first Gurobi optimization code and this is where I am stuck with:
I have the following dictionary for my first subscript:
input for k in range(1,11):
i[k] = int(k)
print i
output {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10}
And, I have the following dictionaries for my second subscript:
c_il = {1: 2, 2: 1, 3: 1, 4: 4, 5: 3, 6: 4, 7: 3, 8: 2, 9: 1, 10: 4}
c_iu = {1: 3, 2: 2, 3: 2, 4: 5, 5: 4, 6: 5, 7: 4, 8: 3, 9: 2, 10: 5}
I am trying to create variables as following:
x = m.addVars(i, c_il, vtype=GRB.BINARY, name="x")
x = m.addVars(i, c_iu, vtype=GRB.BINARY, name="x")
Apparently, it is not giving what I am looking for. What I am looking for is x_(i),(c_il) and x_(i),(c_iu); ignore parenthesis.
More clearly, the following is what I am trying to obtain by using dicts i, c_il, and c_iu:
{1: <gurobi.Var x[1,2]>,
2: <gurobi.Var x[2,1]>,
3: <gurobi.Var x[3,1]>,
4: <gurobi.Var x[4,5]>,
5: <gurobi.Var x[5,3]>,
6: <gurobi.Var x[6,4]>,
7: <gurobi.Var x[7,3]>,
8: <gurobi.Var x[8,2]>,
9: <gurobi.Var x[9,1]>,
10: <gurobi.Var x[10,4]>,
11: <gurobi.Var x[1,3]>,
12: <gurobi.Var x[2,2]>,
13: <gurobi.Var x[3,2]>,
14: <gurobi.Var x[4,5]>,
15: <gurobi.Var x[5,4]>,
16: <gurobi.Var x[6,5]>,
17: <gurobi.Var x[7,4]>,
18: <gurobi.Var x[8,3]>,
19: <gurobi.Var x[9,2]>,
20: <gurobi.Var x[10,5]>}
Since I am using dictionaries everywhere, I want to keep it consistent by continuing to use dictionaries so that I can do multiplications and additions with my parameters which are all in dictionaries. Is there any way to create these variables with m.addVars or m.addVar?
Thanks!
Edit: Modified to make it more clear.
It looks like you want to create 10 variables that are indexed by something. The best way to do this is to create the two indexes as lists. If you want x[12], x[21], then write:
from gurobipy import *
m = Model()
il = [ 12, 21, 31, 44, 53, 64, 73, 82, 91, 104 ]
x = m.addVars(il, vtype=GRB.BINARY, name="x")
And if you want to write x[1,2], x[2,1], then write:
from gurobipy import *
m = Model()
il = [ (1,2), (2,1), (3,1), (4,4), (5,3), (6,4), (7,3), (8,2), (9,1), (10,4) ]
x = m.addVars(il, vtype=GRB.BINARY, name="x")
After a few years of experience, I can easily write the below as an answer. Since the past myself was concerned with keeping the dictionaries as is (I highly criticize and question...), a quick solution is as follows.
x = {}
for (i,j) in c_il.items():
x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%s"%str([i,j]))
for (i,j) in c_iu.items():
x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%s"%str([i,j]))
Alternatively,
x = {(i,j): m.addVar(vtype=GRB.BINARY, name="x%s"%str([i,j]))
for (i,j) in c_il.items()}
for (i,j) in c_iu.items():
x[i,j] = m.addVar(vtype=GRB.BINARY, name="x%s"%str([i,j]))
One liner alternative:
x = {(i,j): m.addVar(vtype=GRB.BINARY, name="x%s"%str([i,j]))
for (i,j) in [(k,l) for (k,l) in c_il.items()] + [(k,l) for (k,l) in c_iu.items()]}

How to take the text of novel as raw_input and put it in ''' '''

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.