This question already has answers here:
Sort a list of objects in Flutter (Dart) by property value
(12 answers)
Closed 12 months ago.
I have a this list
List myList = [
{'name':'user3', 'id':'3'},
{'name':'user5', 'id':'5'},
{'name':'user2', 'id':'2'},
{'name':'user4', 'id':'4'},
{'name':'user1', 'id':'1'}
];
I want to sort this list in the basis of 'id' but I am unable to understand the logic to do so
Basically what I want should be look like this after sorting
List myList = [
{'name':'user1', 'id':'1'},
{'name':'user2', 'id':'2'},
{'name':'user3', 'id':'3'},
{'name':'user4', 'id':'4'},
{'name':'user5', 'id':'5'}
];
You can pass a callback to the sort method that will compare two elements against each other by your custom criteria.
List<Map<String, String>> myList = [
{'name': 'user3', 'id': '3'},
{'name': 'user5', 'id': '5'},
{'name': 'user2', 'id': '2'},
{'name': 'user4', 'id': '4'},
{'name': 'user1', 'id': '1'}
];
void main() {
myList.sort((a, b) => a['id']!.compareTo(b['id']!));
print(myList);
}
Related
I have this:
final data = [
{
'name': 'Team A',
'team': ['Klay Lewis', 'Ehsan Woodard', 'River Bains']
},
{
'name': 'Team B',
'team': ['Toyah Downs', 'Tyla Kane']
},
{
'name': 'Team C',
'team': [
'Jacky Chan',
'Yalor Rowds',
'Tim Bourla',
'Levis Strauss',
'Jane Smow'
]
}
];
I want to find the quickest way to get a sum of all team members. In the above example, it would be 3 + 2 + 5 = 10 total members.
The real world data will have thousands of teams, so quickest way needed.
fold will get the job done.
final int totalLength = data.fold(0, (sum, obj) => sum + obj['team'].length);
import 'package:collection/collection.dart';
const data = [...];
void main(List<String> args) {
var members = data.map((e) => (e['team'] as List).length).sum;
print(members);
}
I am using flutter/dart and I have run into following problem.
I have a list of map like this.
var questions = [
{
'questionText': 'What\'s your favorite color?',
'answer': ['Black', 'Red', 'Green', 'White']
},
{
'questionText': 'What\'s your favorite animal?',
'answer': ['Deer', 'Tiger', 'Lion', 'Bear']
},
{
'questionText': 'What\'s your favorite movie?',
'answer': ['Die Hard', 'Due Date', 'Deep Rising', 'Dead or Alive']
},
];
Now suppose I need to get the string Tiger from this list. How do I do that? Dart is seeing this as List<Map<String, Object>> questions
Maybe a more portable way with a function:
String getAnswer(int question, int answer) {
return (questions[question]['answer'] as List<String>)[answer];
}
// Get 'Tiger'
String a = getAnswer(1, 1);
You can convert object in list in following way and then use index to get any value.
var p = questions[1]['answer'] as List<String>;
print(p[1]);
I'm given this nested dictionary (albeit a bit longer):
stuff = [{'10525083': {'ID': '10525083', 'Score': 25, 'Name': 'Alia Lightside', 'Responses': {'....},
'11004337': {'ID': '11004337', 'Score': 24, 'Name': 'Keebo Keempo', 'Responses': {'....}}]
I need to take all the values relating to the 'Score' key and put them in a list... using list comprehension.
I think it should be something like this but I'm really just throwing stones:
score = [k, v for v in stuff -something something- append? ]
[v.get('Score') for k, v in stuff.items() ]
Is there any nice pythonic way of merging dictionaries within a list?
What I have:
[
{ 'name': "Jack" },
{ 'age': "28" }
]
What I would like:
[
{ 'name': "Jack", 'age': "28" }
]
Here's a method that uses dict.update(). In my opinion it's a very readable solution:
data = [{'name': 'Jack'}, {'age': '28'}]
new_dict = {}
for d in data:
new_dict.update(d)
new_data = [new_dict]
print new_data
OUTPUT
[{'age': '28', 'name': 'Jack'}]
If you're using Python 3, you can use collections.ChainMap:
>>> from collections import ChainMap
>>> ld = [
... { 'name': "Jack" },
... { 'age': "28" }
... ]
>>> [dict(ChainMap(*ld))]
[{'name': 'Jack', 'age': '28'}]
You could use list comprehension:
final_list = [{key: one_dict[key]
for one_dict in initial_list
for key in one_dict.keys()}]
Edit: the list comprehension was backwards
out = reduce(lambda one, two: dict(one.items() + two.items()),
[{'name': 'Jack'}, {'age': '28'}, {'last_name': 'Daniels'}])
print(out)
OUTPUT
{'age': '28', 'last_name': 'Daniels', 'name': 'Jack'}
I have a list:
txtlst = [
['000001', 'DOE', 'JOHN', 'COMSCI', '', 'MATH', '', 'ENGLISH\n'],
['000002', 'DOE', 'JANE', 'FRENCH', '', 'MUSIC', '', 'COMSCI\n']
]
And I want to put the elements in a dictionary so it looks likes this
mydict = {
'000001': ['000001', 'DOE', 'JOHN', 'COMSCI', '', 'MATH', '', 'ENGLISH\n'],
'000002': ['000002', 'DOE', 'JANE', 'FRENCH', '', 'MUSIC', '', 'COMSCI\n']
}
My problem here is, after I ran the code
for i in txtlst:
key = i[0]
value = i
mydict = {key:value}
The two sublists of txtlst are added to different dictionaries. How can I fix my code so they will be in the same dictionary as I mentioned above?
You can easily create a new dictionary with the first element of each list as key:
mydict = { i[0]: i for i in txtlst }
If you wish to do that in a loop like in your approach, you need to initialize a dictionary beforehand and update it in each iteration:
mydict = {}
for i in txtlst:
key = i[0]
value = i
mydict[key] = value