I get data from the a source which I store in variable d
d = {
'0174':
{
'exists': 'Yes',
'order': 4,
},
'0171':
{
'order': 1,
},
'0080': {
'exists': 'Yes',
'order': 0,
},
'0173':
{
'exists': 'No',
'order': 3,
},
'0172':
{
'exists': 'Yes',
'order': 2,
}
}
I have written the below logic that somewhat works,
for w in sorted(d, key=d.get, reverse=True):
print(w, d[w]["shot_order"])
but not perfect.
I want to be able to sort based on the order key in the dict
please help.
You need to use key=lambda outer_key: d[outer_key]['order'] as the sorting key:
for w in sorted(d, key=lambda outer_key: d[outer_key]['order'], reverse=True):
print(w)
Outputs
0174
0173
0172
0171
0080
Related
Suppose I have a List<map> that looks like this:
‘Books’:[
‘B1’{
‘id’: ’1234’,
‘bookName’: ’book1’
},
‘B2’{
‘id’: ’4567’,
‘bookName’: ’book2’
},
‘B3’{
‘id’: ’1234’,
‘bookName’: ’book3’
},
‘B4’{
‘id’: ’8912’,
‘bookName’: ’book4’
},
…
];
I’m trying to return the entire book without duplications in Id.
The expected result should be like this:
‘B1’{
‘id’: ’1234’,
‘bookName’: ’book1’
},
‘B2’{
‘id’: ’4567’,
‘bookName’: ’book2’
},
‘B4’{
‘id’: ’8912’,
‘bookName’: ’book4’
},
I guessed what your input map was and made a solution based on this answer from Basic Coder.
final list = {
'Books':[
{
'id':'1234',
'bookName':'book1'
},
{
'id':'4567',
'bookName':'book2'
},
{
'id': '1234',
'bookName':'book3'
},
{
'id': '8912',
'bookName':'book4'
},
]};
void main() {
print('With duplicates $list');
final ids = list['Books']!.map<String>((e) => e['id']!).toSet();
list['Books']!.retainWhere((Map x) {
return ids.remove(x['id']);
});
print('Without duplicates $list');
}
This code shows your input as the variable list, which seems to be what you were going for with your provided data. The code then obtains a list of each id of the book and removes duplicates by changing it to a Set. Then it only retains elements in the original list with those non-duplicate ids.
Remove the ! operators if you're not using null-safety.
Here's one inspired by Christopher's answer:
void main() {
var books = {
'B1': {
'id': '1234',
'bookName': 'book1',
},
'B2': {
'id': '4567',
'bookName': 'book2',
},
'B3': {'id': '1234', 'bookName': 'book3'},
'B4': {'id': '8912', 'bookName': 'book4'},
};
var seen = <String>{};
var kept = books.entries.where((me) => seen.add(me.value['id'] ?? 'OTHER'));
print(Map.fromEntries(kept));
}
I think it's a bit simpler, since it doesn't have to populate the Set first. I also learned that Set.add returns a bool to indicate the element didn't exist before. Nice.
how i can sort my List by one of my values from list?
here is a example of my list
List data = [
{'name': 'Example1', 'value1': 10, 'value2': 0},
{'name': 'Example2', 'value1': 0, 'value2': 10},
{'name': 'Example3', 'value1': 15, 'value2': 5},
{'name': 'Example4', 'value1': 22.5, 'value2': 10},
];
and so I call it
Column(
children: data.map((info) {
return Container(
child: SizedBox(
child: Row(
children: [
Text(info['name'],),
Text(info['value1'],),
],
),
),
);
}).toList())
this is how my list is listed from top to bottom
how can i sort it by value?
How can I hide an entry if the value is 0?
list.sort() takes a comparator function. A comparator takes two values from the list and compares them to see if swapping is required. Based on what you return, you can control how the lists get sorted. When a positive value is returned, swapping occurs otherwise not.
In your case, let's say you want to sort using value1 in increasing order. You need to tell the comparator to return a positive value when a > b. If you want decreasing order, return a positive value when b > a:
List data = [
{'name': 'Example1', 'value1': 15},
{'name': 'Example2', 'value1': 10},
{'name': 'Example3', 'value1': 5},
{'name': 'Example4', 'value1': 0},
];
// sort in place w.r.t. value1
// CompareTo method just returns first value - second value in case of double
// Try returning b['value1'].compareTo(a['value1']) or b['value1'] - a['value1'] and the result should be in descending order w.r.t value1 property.
data.sort((a,b) => a['value1'].compareTo(b['value1'])); // You can also write a['value1'] - b['value1']
print(data.toString());
// To filter (remove all those elements whose value1 is 0)
List filtered = data.where((a) => a['value1'] != 0).toList(); // Where method takes a function which should return true if you want to keep the item in the filtered list.
print(filtered.toString()); // filtered is the new list with all those elements removed.
and here is the output:
[{name: Example4, value1: 0}, {name: Example3, value1: 5}, {name: Example2, value1: 10}, {name: Example1, value1: 15}]
[{name: Example3, value1: 5}, {name: Example2, value1: 10}, {name: Example1, value1: 15}]
Update:
You can use the filter like this:
Column(
children: data
.where((d) => d['value1'] != 0) // <----- Here :)
.map((info) {
return Container(
child: SizedBox(
child: Row(
children: [
Text(info['name'],),
Text(info['value1'],),
],
),
),
);
}).toList())
This is the code for my list:
Future<List<Map>> queryDb() async {
List localList;
final db = await database;
final allRows = await db.query(TABLE_FAVORITE);
localList = allRows.toList(growable: true);
localList.removeWhere((item) => item[COLUMN_ISFAVORITE] == 0);
publicFavoriteList = localList;
print(localList);
return localList;
}
whenever it gets called it prints:
[{id: 0, isFavorite: 1}, {id: 1, isFavorite: 1}, {id: 2, isFavorite: 1}, {id: 4, isFavorite: 1}]
How can I "cut" this to
[{0}, {1}, {2}, {4}]
Use map to extract the values from the inner Map objects:
var localValues = localList.map((o) => o['id'] as int).toList();
print(localVales);
// Prints: [0, 1, 2, 4]
I have a List<Comment> about food from users.
It looks like this:
[
{userId: 1,
rating: 4.5
},
{userId: 2,
rating: 4.0
},
{userId: 3,
rating: 3.5
},
{userId: 4,
rating: 3.0
}
...
];
I want to get the average rating. AVERAGE = Number of ratings : total user, how do I apply this in dart?
var values = [
{'userId': 1, 'rating': 4.5},
{'userId': 2, 'rating': 4.0},
{'userId': 3, 'rating': 3.5},
{'userId': 4, 'rating': 3.0}
];
var result = values.map((m) => m['rating']).reduce((a, b) => a + b) / values.length;
print(result);
In 2021 dart has the built-in average method from the collection package which can be used on an Iterable.
import 'package:collection/collection.dart';
void main() {
var values = [
{'userId': 1, 'rating': 4.5},
{'userId': 2, 'rating': 4.0},
{'userId': 3, 'rating': 3.5},
{'userId': 4, 'rating': 3.0}
];
var result = values.map((m) => m['rating']!).average;
print(result); // prints 3.75
}
You might also be interested in the .sum method from the same package.
I did this by adding the values with the fold function and then dividing by the total. Here is an example:
var values = [
{'userId': 1, 'rating': 4.5},
{'userId': 2, 'rating': 4.0},
{'userId': 3, 'rating': 3.5},
{'userId': 4, 'rating': 3.0}
];
List<double> ratings = values.map((e) => e.price!).toList();
double sum = ratings.fold(0, (p, c) => p + c);
if (sum > 0) {
double average = sum / ratings.length;
}
My data structure is
companies = [
{name: 'A', ramps: [1, 2]},
{name: 'B', ramps: [3, 4, 5]}
...
]
ramps = [
{id: 1, division: 'accounting', amount: 500},
{id: 2, division: 'sale', amount: 200},
...
]
My goal is to end up with the following data:
groupedByDivision = [
{division: accounting, total: 12000},
{division: sales, total: 6500},
..
]
My first brute-force approach is something like this (note: I've extended Ember.Array with this flatten method:
var ramps = this.get('controller.companies') // this is the array of companies
.get('model')
.mapProperty('ramps')
.flatten();
var temp = {}, data = [];
$.each(ramps, function(index, ramp) {
if ( !(ramp.billingDiv in tempCompanies) ) {
temp[ramp.billingDiv] = ramp.feeChange;
} else {
temp[ramp.billingDiv] += ramp.feeChange;
}
});
$.each(temp, function(division, amount) {
data.push({
'category': division,
'count': amount
});
});
return data;
Any other suggestions? I'm not too familiar with the Ember.Array methods yet, so I'm not aware of all their use cases.