How to remove Map from list in dart - list

How can remove Map from list based on key value in map, in dart
void main() {
List<Map> names = [
{"id": 1, "name": "Bob"},
{"id": 2, "name": "Alex"},
];
names.forEach((element) {
element.keys.where((key) => element[key] == 1).forEach((names.remove));
});
print(names);
}
I try the above code but it does not works for me.
Thanks

names.removeWhere((element) => element["id"] == 1);

Related

how to extract data inside the list of maps and convert it into maps in dart

How can extract data inside the list of maps and convert it into maps in the dart.
Like I have a List of maps ================================================================================================================================================================================================
[
{"business_id":"2",
"business_title":"Spotify",
"business_phone":"(055) 3733783",
"business_email":"Usamashafiq309#gmail.com",
"business_website":"www.spotify.com",
"business_address":"Spotify AB, Regeringsgatans bro, Stockholm, Sweden",
"business_address_longitude":"18.0680873",
"business_address_latitude":"59.33096949999999",
"business_image":"5f84c7a4bbbd0121020201602537380.png",
"business_created_at":"2020-10-20 15:40:17",
"business_category_id":"2",
"cat_id":"2",
"cat_title":"Gym",
"cat_image":"280920201601308237.png"}
,{"business_id":"2",
"business_title":"Spotify",
"business_phone":"(055) 3733783",
"business_email":"Usamashafiq309#gmail.com",
"business_website":"www.spotify.com",
"business_address":"Spotify AB, Regeringsgatans bro, Stockholm, Sweden",
"business_address_longitude":"18.0680873",
"business_address_latitude":"59.33096949999999",
"business_image":"5f84c7a4bbbd0121020201602537380.png",
"business_created_at":"2020-10-20 15:40:17",
"business_category_id":"2",
"cat_id":"2",
"cat_title":"Gym",
"cat_image":"280920201601308237.png"}
]
and convert it like this
[ {"business_id":"2",
"business_title":"Spotify",},
{"business_id": "1",
"business_title": "Pizza Hut",},
]
You can use the map function to apply a function to each element of a list. Then you can create a submap with your map.
Here is a quick exemple:
void main() async {
List l = [
{
"business_id": "2",
"business_title": "Spotify",
"business_phone": "(055) 3733783",
},
{
"business_id": "1",
"business_title": "Pizza Hut",
"business_phone": "(055) 9999999",
}
];
print(extractMap(l));
}
List extractMap(List l) {
return l
.map((element) => Map.fromEntries([
MapEntry('business_id', element['business_id']),
MapEntry('business_title', element['business_title']),
]))
.toList();
}

Dart - find duplicate values on a List

how can I find duplicate values on a list,
Let's say I got a List like this:
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
How I can iterate the list to know if there are users with the same name?
A simple way would be this:
void main() {
List<Map<String, dynamic>> users = [
{ "name": 'John', 'age': 18 },
{ "name": 'Jane', 'age': 21 },
{ "name": 'Mary', 'age': 23 },
{ "name": 'Mary', 'age': 27 },
];
List names = []; // List();
users.forEach((u){
if (names.contains(u["name"])) print("duplicate ${u["name"]}");
else names.add(u["name"]);
});
}
Result:
duplicate Mary
Probably a cleaner solution with extensions.
By declaring:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> getDupes() {
List<E> dupes = List.from(this);
dupes.removeAll(this.toSet().toList());
return dupes;
}
}
then you can find your duplicates by calling List.getDupes()
Note that the function removeAll doesn't exist in my current Dart library, in case you're reading this when they implement it somehow.
Also keep in mind the equals() function. In a List<String>, ["Rafa", "rafa"] doesn't contain duplicates.
If you indeed want to achieve this level of refinement, you'd have to apply a distinctBy function:
extension ListExtensions<E> on List<E> {
List<E> removeAll(Iterable<E> allToRemove) {
if (allToRemove == null) {
return this;
} else {
allToRemove.forEach((element) {
this.remove(element);
});
return this;
}
}
List<E> distinctBy(predicate(E selector)) {
HashSet set = HashSet();
List<E> list = [];
toList().forEach((e) {
dynamic key = predicate(e);
if (set.add(key)) {
list.add(e);
}
});
return list;
}
List<E> getDupes({E Function(E) distinctBy}) {
List<E> dupes = List.from(this);
if (distinctBy == null) {
dupes.removeAll(this.toSet().toList());
} else {
dupes.removeAll(this.distinctBy(distinctBy).toSet().toList());
}
return dupes;
}
}
I had a feeling Rafael's answer had code similar to Kotlin so I dug around and saw that these functions are part of the kt_dart library which basically gets the Kotlin standard library and ports it to Dart.
I come from a Kotlin background so I use this package often. If you use it, you can simply make the extension this much shorter:
extension KtListExtensions<T> on KtList<T> {
KtList<T> get duplicates => toMutableList()..removeAll(toSet().toList());
}
just make sure to add kt_dart on your pubspec: kt_dart: ^0.8.0
Example
final list = ['apples', 'oranges', 'bananas', 'apples'].toImmutableList();
final duplicates = list.duplicates; // should be ['apples'] in the form of an ImmutableList<String>
void main() {
List<String> country = [
"Nepal",
"Nepal",
"USA",
"Canada",
"Canada",
"China",
"Russia",
];
List DupCountry = [];
country.forEach((dup){
if(DupCountry.contains(dup)){
print("Duplicate in List= ${dup}");
}
else{
DupCountry.add(dup);
}
});
}

How to iterate over a json object in Python?

I have a json object contaning currencies as listed below which I need to convert it into my model and save it into the DB. Also is there a way to save the list of models in one go?
{
"results": {
"ALL": {
"currencyName": "Albanian Lek",
"currencySymbol": "Lek",
"id": "ALL"
},
"KWD": {
"currencyName": "Kuwaiti Dinar",
"id": "KWD"
},
"LSL": {
"currencyName": "Lesotho Loti",
"id": "LSL"
},
"MYR": {
"currencyName": "Malaysian Ringgit",
"currencySymbol": "RM",
"id": "MYR"
},
"MUR": {
"currencyName": "Mauritian Rupee",
"currencySymbol": "₨",
"id": "MUR"
}
}
}
I tried this :
for key,value in currencies.results :
#print(currency)
#print(value)
However, I get the following error :
"Too many attribures to unpack, expected 2
Can someone help me with this?
I think it should be like this:
results = currencies.get('results')
for key, value in results.items(): # for python3
print(key, value)
for key, value in results.iteritems(): # python2.7
print(key, value)
You should iterate as
for result in results:
for currency in result:
print(result)

Elastic search 5, search from list by sublist

I'm trying to search from an object that has a list property.
I need to be able to select all object that contains all sublist items.
ex :
If my object has [A,B,C] it should be returned for the given querys :
[A], [A,B], [A,B,C], [A,C], [C,A] ... (Input order doesn't have to match)
But if the sublist contains any element that is not part of the object list, it should not be returned.
ex :
[D], [A,D] ...
Those querys should not be valid.
I've managed to do it for the query with an existing sublist, but not when any item of the sublist doesn't exists.
Any ideas ?
Thanks !
Use comma seperate for sublist query item as a value for match query and set operator value to "and" as following:
Sample of document:
{
"Id": 1,
"Name": "One",
"tags": ["A","B","C"]
}
For sublist:[A,B]:
{
"query": {
"match": {
"tags": {
"query": "A,B",
"operator": "and"
}
}
}
}
I test in ElasticSearch 5.6.0 and 6.1.2
Assuming A, B, C, etc are mapped as keyword types, multiple bool query filter clauses would be one way
var response = client.Search<User>(s => s
.Query(q => +q
.Term(f => f.Badges, "A") && +q
.Term(f => f.Badges, "B") && +q
.Term(f => f.Badges, "C")
)
);
generates the following query
{
"query": {
"bool": {
"filter": [
{
"term": {
"badges": {
"value": "A"
}
}
},
{
"term": {
"badges": {
"value": "B"
}
}
},
{
"term": {
"badges": {
"value": "C"
}
}
}
]
}
}
}
A user document would need to have at least all of A, B and C badges to be considered a match.
A user document may well have other badges in addition to A, B and C; if you need to find documents that have exactly A, B and C, take a look at the terms_set query with a minimum_should_match* value set to the number of passed terms.

autofilling a dict python 2.x

I'm quite new to Python and programming in general, so apologies if this is quite basic or has been asked and answered before. Here is a sample of the data I'm working with:
{
"homeTeam": {
"formation": [
"4",
"4",
"2"
],
"lineupsSorted": [
{
"player": {
"name": "Scott P. Brown",
"slug": "scott-p-brown",
"shortName": "S. P. Brown",
"id": 19889,
"hasImage": true
},
"position": 1,
"shirtNumber": 1,
"substitute": false,
"positionName": "Goalkeeper",
"positionNameshort": "G",
"captain": false
},
{
"player": {
"name": "Carl Winchester",
"slug": "carl-winchester",
"shortName": "C. Winchester",
"id": 110785,
"hasImage": true
},
"position": 2,
"shirtNumber": 27,
"substitute": false,
"positionName": "Midfielder",
"positionNameshort": "M",
"captain": false
},
I am looking to automate populating defined names as I have done manually here:
hometeamPositions =['Goalkeeper','Midfielder','Defender','Defender','Defender','Midfielder','Midfielder','Midfielder','Midfielder','Forward','Forward','Goalkeeper','Defender','Defender','Midfielder','Midfielder','Forward','Forward']
hometeamPlayers = ['S. P. Brown','C. Winchester','M. Onariase','W.
Boyle','J. Cranston','H. Pell','J. Rowe','K. Storer','B. Waters','D.
Wright','D. Holman','R. Lovett','J. Barthram','T. Plavotic','J.
Munns','L. Davis','K. Wootton','J. Dayton']
As I will be repeating this process many hundreds of times with different data (same structure) I was wondering if anyone could give me some tips on automatically building these ranges?
Thanks,
Peter
I'm not sure I understood what is the problem you are trying to solve but I'll try to help.
Assuming you have a dictionary team_dict and you want to create 2 list: hometeamPositions and hometeamPlayers you can use the following code:
hometeamPlayers = []
hometeamPositions = []
for player_dict in teams_dict['homeTeam']['lineupsSorted']:
hometeamPlayers.append(player_dict['player']['shortName'])
hometeamPositions.append(player_dict['positionName'])
The output on your example will be:
hometeamPlayers = ['S. P. Brown', 'C. Winchester']
hometeamPositions = ['Goalkeeper', 'Midfielder']