Retrieve entries from map based on one of the key values - flutter

I have reviewed similar posts but am still failing to line things up with what i'm after.
I want to retrieve all entries from the following map where the condition a particular condition is met.
The simple map
List<Map<String, dynamic>> _playList = [
{'songId': 1, 'setId': 1},
{'songId': 2, 'setId': 1},
{'songId': 3, 'setId': 1},
{'songId': 4, 'setId': 2},
{'songId': 5, 'setId': 3},
{'songId': 6, 'setId': 4},
{'songId': 6, 'setId': 5},
{'songId': 6, 'setId': 6},
{'songId': 6, 'setId': 7},
];
I am trying to use a method which will iterate through this map, find all entries for the int that was passed into the method and then store the results in a new array.
The method I have so far
Future<List<Song>> songFromCurrentSetlist (int setlistId) async {
_playList.forEach((_) => setlistId == _playList.???);
}
Clearly, a bit stuck.
Basically, if 1 is received for setlistId in the parameter list for the method, I am expecting to get back the values 1,2,3 for each of the songIds that exist for setlistId == 1.
Thank you,
Bob

You can create a list of songs and add new songs when your setId match.
Following Example Clear your Idea.
void main(){
List<Map<String, dynamic>> _playList = [
{'songId': 1, 'setId': 1},
{'songId': 2, 'setId': 1},
{'songId': 3, 'setId': 1},
{'songId': 4, 'setId': 2},
{'songId': 5, 'setId': 3},
{'songId': 6, 'setId': 4},
{'songId': 6, 'setId': 5},
{'songId': 6, 'setId': 6},
{'songId': 6, 'setId': 7},
];
List<int> songs = [];
songFromCurrentSetlist (int setlistId) async {
_playList.forEach((index){
if(index['setId'] == setlistId){
songs.add(index['songId']);
}
});
}
songFromCurrentSetlist(1);
print(songs.toList());
}

Instead of Map why you not using model class
Exp:
class Songs{
final int songId;
final int setId;
Songs(this.songId, this.setId);}
ListSongs> _playList
try using this

Related

How to do that a Container follow path of Containers? (AnimatedContainer)

I have a grid of Containers (blue and red containers), and on top of that, a green Container (with StackWidget) which I need move throught red Containers (path)
Is possible to achieve what I need?
I have the grid of containers and a list with path coords
List<Map<int, int>> path = [
{2: 0},
{2: 1},
{2: 2},
{2: 3},
{2: 4},
{3: 4},
{4: 4},
{5: 4},
{5: 5},
{5: 6},
{5: 7},
//...

Using map in spark to make dictionary format

I executed the following code:
temp = rdd.map( lambda p: ( p[0], (p[1],p[2],p[3],p[4],p[5]) ) ).groupByKey().mapValues(list).collect()
print(temp)
and I could get data:
[ ("A", [("a", 1, 2, 3, 4), ("b", 2, 3, 4, 5), ("c", 4, 5, 6, 7)]) ]
I'm trying to make a dictionary with second list argument.
For example I want to reconstruct temp like this format:
("A", {"a": [1, 2, 3, 4], "b":[2, 3, 4, 5], "c":[4, 5, 6, 7]})
Is there any clear way to do this?
If I understood you correctly you need something like this:
spark = SparkSession.builder.getOrCreate()
data = [
["A", "a", 1, 2, 5, 6],
["A", "b", 3, 4, 6, 9],
["A", "c", 7, 5, 6, 0],
]
rdd = spark.sparkContext.parallelize(data)
temp = (
rdd.map(lambda x: (x[0], ({x[1]: [x[2], x[3], x[4], x[5]]})))
.groupByKey()
.mapValues(list)
.mapValues(lambda x: {k: v for y in x for k, v in y.items()})
)
print(temp.collect())
# [('A', {'a': [1, 2, 5, 6], 'b': [3, 4, 6, 9], 'c': [7, 5, 6, 0]})]
This is easily doable with a custom Python function once you obtain the temp object. You just need to use tuple, list and dict manipulation.
def my_format(l):
# get tuple inside list
tup = l[0]
# create dictionary with key equal to first value of each sub-tuple
dct = {}
for e in tup[1]:
dct2 = {e[0]: list(e[1:])}
dct.update(dct2)
# combine first element of list with dictionary
return (tup[0], dct)
my_format(temp)
# ('A', {'a': [1, 2, 3, 4], 'b': [2, 3, 4, 5], 'c': [4, 5, 6, 7]})

Dart // Flutter: How to remove Items from List depending on content of entry

In my Flutter app, I have a database which keeps track of which items the user liked and which he disliked. I have the function
List finalFavoritesList;
void queryDb() async {
final db = await database;
final allRows = await db.query(TABLE_FAVORITE);
List finalFavoritesList = allRows.toList(growable: true);
print(finalFavoritesList);
}
which in my understanding creates a dart list from the sqflite database. Logcat prints:
[{id: 0, isFavorite: 0}, {id: 1, isFavorite: 1}, {id: 2, isFavorite: 0}, {id: 3, isFavorite: 1}, {id: 4, isFavorite: 0}, {id: 5, isFavorite: 1}]
Now I want to remove every entry, where isFavorite is equal to 0 but I don't know how. This new list should have another name.
I think your question itself has an answer!
Use removeWhere function.
List favorite = [{'id': 0, 'isFavorite': 0}, {'id': 1, 'isFavorite': 1}, {'id': 2, 'isFavorite': 0}, {'id': 3, 'isFavorite': 1}, {'id': 4, 'isFavorite': 0}, {'id': 5, 'isFavorite': 1}];
favorite.removeWhere((item) => item['isFavorite'] == 0);
print(favorite);
Output:
[{id: 1, isFavorite: 1}, {id: 3, isFavorite: 1}, {id: 5, isFavorite: 1}]
Refer: https://api.dart.dev/stable/2.9.3/dart-core/List/removeWhere.html
Hope that solves your case!

Generate list of values, based on matching keys

I have the below dictionary:
{'Closed': {'High': 33, 'Medium': 474, 'Low': 47, 'Critical': 6}, 'Impact Statement Pending': {'Low': 3, 'Medium': 1, 'Critical': 0, 'High': 0}, 'New': {'Low': 1, 'High': 2, 'Critical': 2, 'Medium': 2}, 'Remediation Plan Pending': {'Medium': 10, 'Low': 1, 'Critical': 1, 'High': 0}, 'Remedy in Progress': {'Medium': 36, 'Low': 18, 'High': 4, 'Critical': 1}}
How might I accomplish creating a list comprised of all values for a specified key? A list for all high values, or another list for all medium values?
The way I am currently accomplishing this doesn't seem like the best way. I've got a list of all severity levels, which I iterate over and compare such as shown below:
trace_list = ['High', 'Medium', 'Critical', 'Low']
total_status_dict = {'Closed': {'High': 33, 'Medium': 474, 'Low': 47, 'Critical': 6}, 'Impact Statement Pending': {'Low': 3, 'Medium': 1, 'Critical': 0, 'High': 0}, 'New': {'Low': 1, 'High': 2, 'Critical': 2, 'Medium': 2}, 'Remediation Plan Pending': {'Medium': 10, 'Low': 1, 'Critical': 1, 'High': 0}, 'Remedy in Progress': {'Medium': 36, 'Low': 18, 'High': 4, 'Critical': 1}}
for item in trace_labels:
y_values = []
for key, val in total_status_dict.items():
for ke in total_status_dict[key]:
if item is ke:
y_values.append(total_status_dict[key][ke])
Note: you are iterating over total_status_dict keys and appending results to a list. Remember that even if dictionaries are officially ordered in Python since 3.7 (see https://docs.python.org/3/whatsnew/3.7.html) you do not always control the Python version of the user. I would rather build a dict key -> item -> value, where key is Closed, Impact Statement Pending, ... and  item is one of the trace_labels than a dict key -> [values] where values is supposed to be ordered as in trace_labels.
Your code is not efficient because you iterate over trace_labels twice:
for item in trace_labels:
for ke intotal_status_dict[key]: if item is ke:`
How to iterate only once? Instead of building y_values lists one by one (with a whole iteration over total_status_dict each time), you can build several lists at once:
>>> trace_labels = ['High', 'Medium', 'Critical', 'Low']
>>> total_status_dict = {'Closed': {'High': 33, 'Medium': 474, 'Low': 47, 'Critical': 6}, 'Impact Statement Pending': {'Low': 3, 'Medium': 1, 'Critical': 0, 'High': 0}, 'New': {'Low': 1, 'High': 2, 'Critical': 2, 'Medium': 2}, 'Remediation Plan Pending': {'Medium': 10, 'Low': 1, 'Critical': 1, 'High': 0}, 'Remedy in Progress': {'Medium': 36, 'Low': 18, 'High': 4, 'Critical': 1}}
>>> y_values_by_label = {}
>>> for key, value_by_label in total_status_dict.items():
... for label, value in value_by_label.items(): # total_status_dict[key] is value_by_label
... y_values_by_label.setdefault(label, {})[key] = value
...
>>> y_values_by_label
{'High': {'Closed': 33, 'Impact Statement Pending': 0, 'New': 2, 'Remediation Plan Pending': 0, 'Remedy in Progress': 4}, 'Medium': {'Closed': 474, 'Impact Statement Pending': 1, 'New': 2, 'Remediation Plan Pending': 10, 'Remedy in Progress': 36}, 'Low': {'Closed': 47, 'Impact Statement Pending': 3, 'New': 1, 'Remediation Plan Pending': 1, 'Remedy in Progress': 18}, 'Critical': {'Closed': 6, 'Impact Statement Pending': 0, 'New': 2, 'Remediation Plan Pending': 1, 'Remedy in Progress': 1}}
setdefault(label, {}) creates a empty dict y_values_by_label[label] = {} if y_values_by_label does not have the key label.
If you want to turn this in a dict comprehension, you have to use your inefficient method:
>>> {label:{k:v for k, value_by_label in total_status_dict.items() for l, v in value_by_label.items() if l==label} for label in trace_labels}
{'High': {'Closed': 33, 'Impact Statement Pending': 0, 'New': 2, 'Remediation Plan Pending': 0, 'Remedy in Progress': 4}, 'Medium': {'Closed': 474, 'Impact Statement Pending': 1, 'New': 2, 'Remediation Plan Pending': 10, 'Remedy in Progress': 36}, 'Critical': {'Closed': 6, 'Impact Statement Pending': 0, 'New': 2, 'Remediation Plan Pending': 1, 'Remedy in Progress': 1}, 'Low': {'Closed': 47, 'Impact Statement Pending': 3, 'New': 1, 'Remediation Plan Pending': 1, 'Remedy in Progress': 18}}

Sorting Dictionary on two values in swift

I have the following dictionary like so:
["FLBEY023": ["Position": 8, "Page": 1],
"COSMAX826": ["Position": 6, "Page": 2],
"TOVIC029": ["Position": 7, "Page": 1],
"CGLYN188": ["Position": 2, "Page": 2],
"TOORL002B": ["Position": 1, "Page": 2],
"GSTOGFU096": ["Position": 6, "Page": 1],
"COSNAI423": ["Position": 2, "Page": 1],
"COSCOL681": ["Position": 3, "Page": 2],
"TONIV170": ["Position": 4, "Page": 1],
"SUMAL086A": ["Position": 7, "Page": 2],
"PEIAM004": ["Position": 5, "Page": 1],
"FOSCI012": ["Position": 1, "Page": 1],
"FOSWI009": ["Position": 4, "Page": 2],
"GSTODOV061": ["Position": 3, "Page": 1]]
Now I'd like to sort this Dictionary for each of the product codes. But I'd like to sort it on position and page. So for example I'd like it to run position then page number for example
["FOSCI012": ["Position": 1, "Page": 1],
"COSNAI423": ["Position": 2, "Page": 1],
"GSTODOV061": ["Position": 3, "Page": 1],
....
...
...
"TOORL002B": ["Position": 1, "Page": 2],
"CGLYN188": ["Position": 2, "Page": 2],
..
How would I go about doing this using the Dictionary.sorted method. I understand how to do it to sort based on one element but not two.
Dictionaries are unordered collections and you can't sort them.
However, you can use .sorted(by:) method that returns a list of ordered tuples where each one represents a key-value entry in the dictionary:
dictionary.sorted { (lhs, rhs) -> Bool in
if (lhs.value["Page"]! == rhs.value["Page"]!) {
return lhs.value["Position"]! < rhs.value["Position"]!
} else {
return lhs.value["Page"]! < rhs.value["Page"]!
}
}
which results in sth like below:
[(key: "FOSCI012", value: ["Position": 1, "Page": 1]),
(key: "COSNAI423", value: ["Position": 2, "Page": 1]),
...
(key: "TOORL002B", value: ["Position": 1, "Page": 2]),
(key: "CGLYN188", value: ["Position": 2, "Page": 2]),
...
]
Here you can download the playground.
You can sort dictionary by key and value
extension Dictionary where Value:Comparable {
var sortedByValue:[(Key,Value)] {return Array(dict).sorted{$0.1 < $1.1}}
}
extension Dictionary where Key:Comparable {
var sortedByKey:[(Key,Value)] {return Array(dict).sorted{$0.0 < $1.0}}
}
["b":2,"a":1,"c":3].sortedByKey// output will be a:1, b:2, c:3
["b":2,"a":1,"c":3].sortedByValue//output will be a:1, b:2, c:3