Looping through a nested python dictionary with key references - key-value

I have a dictionary which looks something like this-
{
'a': ['1','2','3','d'],
'b': ['x','y','z'],
'c': ['a','10'],
'd': ['x','5'],
'e': ['6'],
'y': ['11','12']
'x': ['0']
'z': ['a']
}
I am trying to resolve all the key references inside the list associated with key. So the final output should look like the following:
{
'a': ['1','2','3','0','5'],
'b': ['0','11','12','1','1','2','3','0','5'],
'c': ['1','2','3','0','5','10'],
'd': ['0','5'],
'e': ['6'],
'y': ['11','12']
'x': ['0']
'z' :['1','2','3','0','5']
}
I am trying to come up with a way where I can either rewrite the original dictionary with the resolved value or create a new dictionary with the resolved values.

Related

Firebase Realtime DB query returns both a list and a map when using startAfter

I have the following piece of code, that is simplified for the purpose of illustration:
List<Name> _nameList = [];
_getNameList() {
String dbPath = “names/“;
var startAfter = _nameList.length - 1;
final db = FirebaseDatabase.instance
.ref()
.child(dbPath)
.orderByKey()
.startAfter(startAfter.toString())
.limitToFirst(4);
final nameFuture = db.once();
nameFuture.then((event) {
List<Name> nameList = [];
print(event.snapshot.value);
if (event.snapshot.value != null) {
for (var item in (event.snapshot.value as List<Object?>)) {
if (item != null) {
Name d = Name.fromRTDB(item);
nameList.add(d);
}
}
}
if (nameList.isNotEmpty) {
setState(() {
_nameList.addAll(nameList);
});
}
});
}
It initially reads the first 4 Name objects from Firebase Realtime DB. And whenever it is called, I expect it to read the very next 4 Name objects and attach them to the _nameList as stated in the code.
IMPORTANT to note that keys to each Name object in the Realtime DB are as 0, 1, 2, 3, 4, and so on. If I am not totally wrong, this actually should make the life easier when using startAfter.
As you may recognize, I print out the values coming from DB, as print(event.snapshot.value);.
The first read works perfectly fine, where startAfter is set to "-1". Example output from print(event.snapshot.value);:
[{name: "John"}, {name: "Johanna"}, {name: "Maria"}, {name: "Steve"}]
Problem 1
When I run the function again, where the startAfter is now 3, I see the following output:
[null, null, null, null, {name: "Michael"}, {name: "Maradona"}, {name: "Pelle"}, {name: "Messi"}]
I expect the list to have the size of 4 but it includes 8 items. And the first 4 are null. Why do I have 8 items in the returned list, and why are the first 4 null?
Problem 2
When I run the function for the 3rd time, where the startAfter is now 7, I get the following output this time:
{10: {name: "Jordan"}, 8: {name: "James"}, 9: {name: "Rambo"}, 11: {name: "Brian"}}
While the first 2 calls returned lists, the 3rd call returned a map.
Why does it all of a sudden return a map in the 3rd call?
And I make the call with orderByKey() but the returned keys in the map are not in order; why?
Problem 1: When I run the function again, where the startAfter is now 3, I see the following output:
[null, null, null, null, {name: "Michael"}, {name: "Maradona"}, {name: "Pelle"}, {name: "Messi"}]
This is the expected behavior for the Realtime Database API. When it sees a bunch of (sufficiently) sequential numeric keys, it assumed that data was originally an array and returns the data as an array. Since your array doesn't have items at indexes [0-3] those indexes show us as null.
This so-called array coercion depends very much on the data, but typically stops happening once there are too many (I don't recall the exact value for that) missing values at the start of the array, which I think is what may be causing the other problem.
The solution is to not use sequential numeric keys in your Realtime Database data, but either use the push() function to generate keys (recommended) or to prefix the numbers with a short string, e.g. "key_3", "key_4", etc.
Also see: Best Practices: Arrays in Firebase.

How to add a new value to Map in Dart?

this is my first post to StackOverflow.
I have been struggling with the Map data.
It’s been taking too much time to find a way more than I thought...
Ex)
Map<String, int> someMap = {
"a": 1,
"b": 2,
"c": 3,
};
How can I add a new value to the same key Map?
like this.
a:1, b:2, c:3,4,5,6etc....
I'd be grateful if you could tell me the correct way.
Thank you.
If you want multiple values for the same key, you'll need to change the value type: Right now it's int, but that can only be a single int, and by definition, a key only occurs once in a map.
If you change the type of the value to List<int>, you can add multiple values for the same key:
Map<String, List<int>> someMap = {
"a": [1],
"b": [2,3],
"c": [4],
};
Now, to add more values, you could simply access the list and add values to it:
someMap["c"].add(5); // c: [4, 5]
someMap["c"].addAll([6,7,8]); // c: [4, 5, 6, 7, 8]

How to get the length for each list according to its key inside map

how to get the length for each list according to its key
Map mymap= <String, List>;
Example
key1 : 5(length of the value(list))
key2 : 48
It seems similar to this,
you can do mymap['k1']?.length, here ?. means it will return null if there is no value.
Rest you can follow #zabaykal's answer.
Map<String, List> mymap = {
"k1": [1, 2, 4],
"k2": [5, 6, 7],
"k3": []
};
print(mymap['k1']?.length);
mymap.forEach((key, value) {
print('$key: ${value.length}');
});
If you want to create a second map with the original keys and the respective lengths as the value you can use the following code where initialMap is the original map with List<T> as values:
final mapListCount = initialMap.map((key, value) => MapEntry(key, value?.length));

Flutter dropdown can't have duplicate values? But unfortunately I have those as it is fetching from an API

My dropdown is having duplicate values as it is fetching Pincode data from an API. Can someone help me to fix this error as the dropdown cant have duplicate values? How to stop duplicate values while fetching the data from the API?enter image description here
You can convert your list to set and then again back to list for to delete duplicated values. Set doesnt contain duplicated values. For more check out documentation of set
void main() {
final myList = [
{
'a': 'apple',
'name':'sam',
'age': 41,
},
{
'a': 'apple',
'name':'alex',
'age': 43,
},
{
'a': 'ban',
'name':'robby',
'age': 41,
}
];
var uniqueIds = myList.map((o) => o["a"]).toSet().toList();
print(uniqueIds);
}
Mapping the list with specific key and then => conversion of toSet() and toList() solves my problem

How to convert a `List` to `Set` using literals

final _set = [1, 1, 2, 3, 4].toSet();
besides effective dart suggesting prefer_collection_literals
it really looks like java or c# rather than dart (no offense)
does anybody knows
How to convert a List to Set using literals
(suggesting to add // ignore: prefer_collection_literals isn't an answer)
You can do something like this:
main() {
final list = [1, 1, 2, 3, 4];
final _set = {...list};
print('set: $_set'); // set: {1, 2, 3, 4}
}
You can write the same code as final _set = {1, 1, 2, 3, 4};.
When you write {key: value, key: value} that is a Map literal, but if you just do {value, value, ...} that becomes a Set literal.