Remove elements from List that are missing in another list - list

I would like to remove from List a elements that are not in another List. Suppose I have
List a = [{"id": 1}, {"id": 2}, {"id": 4}, {"id": 7},]
List b = [{"id": 1}, {"id": 2}, {"id": 7},]
Then I would like to remove from List a the element {"id": 4}, since it is missing in List b
If List b were
List b = [{"id": 1}, {"id": 2}, {"id": 4},]
then I would like to remove from List a element {"id": 7}
How to do this in Flutter.
Thank you.

void main() {
var a = [{"id": 1}, {"id": 2}, {"id": 4}, {"id": 7}];
var b = [{"id": 1}, {"id": 2}, {"id": 7}];
var c = a.map((m) => m['id']);
var d = b.map((m) => m['id']);
var e = c.toSet().difference(d.toSet());
var f = a.where((m) => e.contains(m['id']));
print(f);
}
Result
({id: 4})

I fixed it like this
List a = [{"id": 1}, {"id": 2}, {"id": 4}, {"id": 7}];
List b = [{"id": 1}, {"id": 2}, {"id": 7}];
a.removeWhere((elementA) => b.every((elementB) =>
elementB["id"] != elementA["id"]));

Related

Merging a list of dictionaries

I have a list of dicts as below.
list = [ {id: 1, s_id:2, class: 'a', teacher: 'b'} ]
list1 = [ {id: 1, c_id:1, rank:2, area: 34}, {id:1, c_id:2, rank:1, area: 21} ]
I want to merge the two lists on the common key-value pairs (in this case 'id:1')
Merged_list = [ {id:1, s_id:2, class: 'a', teacher: 'b', list1: {c_id:1, rank: 2, area: 34}, {c_id:2, rank: 1, area: 21} ]
How do I go about this?
Thanks
You can use
merged_list = [{**d1, **d2} for d1, d2 in zip(list1, list2)]
>>> merged_list
[{'id': 1, 's_id': 2, 'class': 'a', 'teacher': 'b', 'rank': 2, 'area': 34},
{'id': 2, 's_id': 3, 'class': 'c', 'teacher': 'd', 'rank': 1, 'area': 21}]
where {**d1, **d2} is just a neat way to combine 2 dictionaries. Keep in mind this will replace the duplicate keys of the first dictionary. If you're on Python 3.9, you could use d1 | d2.
EDIT: For the edit in your question, you can try this horrible one liner (keep in mind this will create the pair list1: [] if no matching indeces were found on list1):
list_ = [{"id": 1, "s_id": 2, "class": 'a', "teacher": 'b'}]
list1 = [{"id": 1, "c_id": 1, "rank": 2, "area": 34}, {"id": 1, "c_id": 2, "rank": 1, "area": 21}]
merged_list = [{**d, **{"list1": [{k: v for k, v in d1.items() if k != "id"} for d1 in list1 if d1["id"] == d["id"]]}} for d in list_]
>>> merged_list
[{'id': 1,
's_id': 2,
'class': 'a',
'teacher': 'b',
'list1': [{'c_id': 1, 'rank': 2, 'area': 34},
{'c_id': 2, 'rank': 1, 'area': 21}]}]
This is equivalent to (with some added benefits):
merged_list = []
for d in list_:
matched_ids = []
for d1 in list1:
if d["id"] == d1["id"]:
d1.pop("id") # remove id from dictionary before appending
matched_ids.append(d1)
if matched_ids: # added benefit of not showing the 'list1' key if matched_ids is empty
found = {"list1": matched_ids}
else:
found = {}
merged_list.append({**d, **found})
Try this
And don't forget to put " " when declare string
list = [ {"id": 1, "s_id": 2 ," class": 'a', "teacher": 'b'}, {"id": 2, "s_id" : 3, "class" : 'c', "teacher": 'd'} ]
list1 = [ {"id": 1, "rank" :2, "area" : 34}, {"id" :2, "rank" :1, "area": 21} ]
list2 = list1 + list
print(list2)

What's the best way to sort MAP<String, Object> by value in Dart programming?

I'm new to dart programming, I came from a Javascript environment
everything is fresh to me and I really have no Idea how this sorting works
in dart.
Here's an example from my API
List example = [
{"id": "1", "age": "20"},
{"id": "2", "age": "21"},
{"id": "3", "age": "22"},
]
Before I will assign "example" to other variables eg.
var example2 = example;
I want to sort it by "age", I found libs and other "LONG" solutions out there but feels like there's another way.. Thanks in advance!
There is sort function for list. Try reading the documentation a bit:
void main() {
List example = [
{"id": "1", "age": "20"},
{"id": "2", "age": "19"},
{"id": "3", "age": "22"},
{"id": "4", "age": "9"},
];
print(example);
example.sort((x,y) => x["age"].compareTo(y["age"]));
print(example);
}
EDIT: Your definition should contain integers logically:
void main() {
List example = [
{"id": 1, "age": 20},
{"id": 2, "age": 19},
{"id": 3, "age": 22},
{"id": 4, "age": 9},
];
print(example);
example.sort((x,y) => x["age"].compareTo(y["age"]));
print(example);
}

How to add a list in a list to another list

I have a list called test3 and I want to add this list to another list test0. The problem is that I only want the "noequipment" "sublist" to be added to the test0.
I tried it with the following code:
var test0 = test0 + test3["noequipment"];
This is list test3:
var test3 = [
{
"noequipment": [
{"name": "test0.1", "time": 10},
{"name": "test0.2", "time": 10},
{"name": "test0.3", "time": 10},
{"name": "test0.4", "time": 10},
]
},
{
"equipment1": [
{"name": "test1.1", "time": 10},
{"name": "test1.2", "time": 10},
{"name": "test1.3", "time": 10},
{"name": "test1.4", "time": 10},
]
},
];
Maybe you are looking for this answer
for (var i in test3[0]['noequipment']) {
test0.add(i);
print("===========>>${test0}");
}
Use code below assuming test0 is already an array
test0.addAll(test3[0]['noequipment'])
Please test this code.
test0.addAll(test3[0]["noequipment"]);
Make sure parent list is defined as var test0 = [] ;
Here I test this code https://pastebin.pl/view/ff02c9cc

How to generate a reliable `hasMoreResults` value for pagination in DynamoDB queries

I am trying to perform pagination on a simple DynamoDB table for queries by date range, and had hoped to coerce the LastEvaluatedKey into a "hasMoreResults" boolean value for my front end to consume, but now see that a non-empty LastEvaluatedKey can sometimes appear on results even when the number of items within the date range does not exceed my LIMIT. Does this mean that I will always need to perform a subsequent query that will return no additional items?
My table looks something like:
[
{PK: "john", SK: "2021-01-01:08:00", amount: 1},
{PK: "john", SK: "2021-01-01:20:00", amount: 2},
{PK: "john", SK: "2021-01-02:08:00", amount: 3},
{PK: "john", SK: "2021-01-02:20:00", amount: 4},
{PK: "john", SK: "2021-01-03:08:00", amount: 5},
{PK: "john", SK: "2021-01-03:20:00", amount: 6}
...and on for all of January
];
Using the JavaScript DocumentClient, my query looks like:
async function getEntriesByDate({name, startDate, endDate, limit, sort}) {
return await docClient.query({
TableName: "someTableName",
KeyConditionExpression: "#pk = :pk and #sk Between :startDate And :endDate",
ExpressionAttributeNames: {
"#pk": "PK",
"#sk": "SK"
},
ExpressionAttributeValues: {
":pk": name,
":startDate": startDate,
":endDate": endDate
},
ScanIndexForward: sort === "asc",
Limit: limit
}).promise();
}
If I call the function with the end date exactly matching the date of the fourth item and a LIMIT of 4:
getEntriesByDate({name: "john", startDate: "2021-01-01:08:01", endDate: "2021-01-02:20:01", limit: 4, sort:"asc"});
I get the following result:
{
"Items": [
{"PK": "john", "SK": "2021-01-01:08:00", "amount": 1},
{"PK": "john", "SK": "2021-01-01:20:00", "amount": 2},
{"PK": "john", "SK": "2021-01-02:08:00", "amount": 3},
{"PK": "john", "SK": "2021-01-02:20:00", "amount": 4 }
],
"Count": 4,
"ScannedCount": 4
}
Great, there's no LastEvaluatedKey. which is what I expect. But if I call the function with the same args except adding a minute to the end date, I get:
{
"Items": <same as in last query, which is expected>,
"Count": 4,
"ScannedCount": 4,
"LastEvaluatedKey": {
"SK": "2021-01-02:20:00",
"PK": "john"
}
}
and LastEvaluatedKey does appear, even though there are no additional items that satisfy the query. Is there an idiomatic solution to this problem? Is a subsequent query, perhaps using ExclusiveStartKey, necessary inside my function in order to secure a reliable hasMoreResults value?

Extracting value from dictionary in a list

I have this list with dictionaries:
[{"Name": "Tore", "Score": 7}, {"Name": "Arne", "Score": 10}, {"Name": "Terje", "Score": 4}]
and want to put the information in variables so i can get this:
first = "Tore
first_number = 7
second = "Arne
second-number = 10
How do I access these values in these variables?
Tried allot of different ways, but neither works.