I have
Map<String,List<String>> myMap = {'1': ['A','B','C'], '2': ['D','E','F'], '3': ['G','H','I'] };
I would like to know how I can reverse the list values. This is what I want to achieve:
Map<String,List<String>> myMap = {'1': ['C','B','A'], '2': ['F','E','D'], '3': ['I','H','G'] };
You can do it like this :
void main() {
Map<String,List<String>> myMap = {'1': ['A','B','C'], '2': ['D','E','F'], '3': ['G','H','I'] };
Map<String,List<String>> reversedMap = {};
myMap.forEach((key,value) {
reversedMap[key] = value.reversed.toList();
});
print(reversedMap);
}
OUTPUT :
{1: [C, B, A], 2: [F, E, D], 3: [I, H, G]}
data.map((key, value) => MapEntry(key, value.reversed.toList()));
Note: this produce a new map. See more in comment.
Related
I have a map
Map<String, List> map1 = {a: [1,2,3,4], b: [5,6,7,8], c: [9,10,11]};
I know one of the values of one of the lists - 1..11.
How can I get the key of a map entity where this value belongs to - a, b, c?
Try this, where search is the value you're trying to find in the array.
Note that firstWhere can give you an error if the value cannot be found anywhere.
void main() {
final data = {
'a': [1, 2, 3, 4],
'b': [5, 6, 7, 8],
'c': [9, 10, 11]
};
final search = 4;
final selected = data.keys.firstWhere((key) {
return data[key]!.contains(search);
});
print(selected); // a
}
I found a solution
int valueToLookFor = 5;
String keyName = map1.keys.firstWhere((key) => map1[key]!.contains(valueToLookFor));
list1 = [{'a': 'a1', 'b': 'b1', 'c': 'c1'}]
if I want to change 'a1' value to a2, how can i do that?
also, with changing a1 to a2, I also have to preserve list1 and make new list.
there are no any questions about this in this site....
There are not lists, they are dictionaries. You don't need the square brackets.
dict1 = {'a': 'a1', 'b': 'b1', 'c': 'c1'}
To copy a dictionary use .copy()
dict2 = dict1.copy()
To replace the value of keyname a use.
dict2['a'] = 'a2'
print(dict1)
print(dict2)
Output:
{'a': 'a1', 'b': 'b1', 'c': 'c1'}
{'a': 'a2', 'b': 'b1', 'c': 'c1'}
If, for some reason, you do really want your dictionary inside a list, you can modify the values by addressing it's position in the list and then the dictionary key. In your case, there is one dictionary with index 0 in the list.
dict2[0]['a'] = 'a2'
For code below:
a = dict()
x = ['a','b','c']
y = [1,2,3,4,5,6]
z = ['p','q']
for zz in z:
a[zz] = dict((xx,yy) for xx,yy in zip(x,(t for t in y)))
print a
I am getting:
{'q': {'a': 1, 'c': 3, 'b': 2}, 'p': {'a': 1, 'c': 3, 'b': 2}}
But, the dictionary I am expecting is:
{'q': {'a': 4, 'c': 6, 'b': 5}, 'p': {'a': 1, 'c': 3, 'b': 2}}
Am I doing something wrong? Is there any logical error in the code?
Each time through your for block, the t for t in y (which I assume was just an attempt to make something work when y alone didn't work?) is started over, so you're always going to get the first elements from the y list. One way to get it to keep its position each time through would be to turn it into an iterator:
y = iter([1,2,3,4,5,6])
While you're at it, you might as well turn the (t for t in y) back into simply y.
What about:
a = dict()
x = ['a','b','c']
y = [1,2,3,4,5,6]
z = ['p','q']
for i, zz in enumerate(z):
a[zz] = dict((xx,yy) for xx,yy in zip(x*(i+1),y))
print a
In the original code, the zip(x, (t for t in y)) part will always cut the end off of the longer of the two lists.
Say I have a list of items:
Seq(A, B, B, B, B, G, G, S, S, S, B, A, G)
And I want to find all the chains and get a sequence of them like so:
Seq(Seq(A), Seq(B, B, B, B), Seq(G, G), Seq(S, S, S), Seq(B), Seq(A), Seq(G))
I want to maintain order, and use a custom comparison function to decide if two objects are the "same". I'm thinking a fold or a scan may be what I need, but I'm having trouble coming up with the exact case. I'm using Scala.
EDIT: I've modified the answer from that similar question to get this:
def collapse(input: Seq[Stmt]): Seq[Seq[Stmt]] = {
val (l, r) = input.span(_.getClass == input.head.getClass)
l :: collapse(r)
}
Cleaner solution:
def pack[T](input: List[T]): List[List[T]] =
input.foldRight(Nil : List[List[T]]) ((e, accu) => accu match {
case Nil => List(List(e))
case curList#(h :: t) if e == h => List(e) :: curList
case curList#(h :: t) => List(List(e)) ::: curList
})
Not using any library functions (ugly):
def pack[T](input: List[T]): List[List[T]] = {
def packWithPrevious(remaining: List[T])(previous: List[T]): List[List[T]] =
remaining match {
case List() => List(previous)
case head :: tail =>
val nextIter = packWithPrevious(tail)(_)
previous match {
case List() => nextIter(List(head))
case prevHead :: _ =>
if (head != prevHead)
previous :: nextIter(List(head))
else
nextIter(head :: previous)
}
}
packWithPrevious(input)(List())
}
scala> val s = List('A', 'B', 'B', 'B', 'B', 'G', 'G', 'S', 'S', 'S', 'B', 'A', 'G')
s: List[Char] = List(A, B, B, B, B, G, G, S, S, S, B, A, G)
scala> pack(s)
res2: List[List[Char]] = List(List(A), List(B, B, B, B), List(G, G), List(S, S, S), List(B), List(A), List(G))
Source: https://github.com/izmailoff/scala-s-99/blob/master/src/main/scala/s99/p09/P09.scala
Test: https://github.com/izmailoff/scala-s-99/blob/master/src/test/scala/s99/p09/P09Suite.scala
Similar to existing answers but I find using a partial function directly in foldLeft as a clean solution:
val s = Seq("A", "B", "B", "B", "B", "G", "G", "S", "S", "S", "B", "A", "G")
s.foldLeft(Seq[Seq[String]]()) {
case (Seq(), item) => Seq(Seq(item))
case (head::tail, item) if head.contains(item) => (item +: head) +: tail
case (seq, item) => Seq(item) +: seq
}.reverse
res0: Seq[Seq[String]] = List(List(A), List(B, B, B, B), List(G, G), List(S, S, S), List(B), List(A), List(G))
Consider following solution:
seq.foldLeft(List(List(seq.head))) { case (acc,item)=>
if(acc.head.head==item) (item::acc.head)::acc.tail else List(item)::acc
}.reverse
seq may be empty, so:
seq.foldLeft(List(seq.headOption.toList)) { case (acc,item)=>
if(acc.head.head==item) (item::acc.head)::acc.tail else List(item)::acc
}.reverse
I thought groupBy would be helpful here, but my solution got slightly awkward:
val seq = Seq("A", "B", "B", "B", "B", "G", "G", "S", "S", "S", "B", "A", "G")
val parts = {
var lastKey: Option[(Int, String)] = None
seq.groupBy(s => {
lastKey = lastKey.map((p: (Int, String)) =>
if (p._2.equalsIgnoreCase(s)) p else (p._1 + 1, s)) orElse Some((0, s))
lastKey.get
}).toSeq.sortBy(q => q._1).flatMap(q => q._2)
}
(using equalsIgnoreCase as example for a comparision function)
here is my list:
projects = ["A", "B", "C"]
hours = [1,2,3]
I want my final answer to be like: {A:1,B:2,C:3}
Is there any suggestion?
Did you try to call dict constructor?
dict(zip(projects,hours))
The code fragment zip(projects,hours) will generate a list of tuples (key,value) which will be used to feed the map (usually called dictionary in python) constructor: dict
In Python 2.7 is also "dictionary comprehension"
>>> projects = ["A", "B", "C"]
>>> hours = [1,2,3]
>>> res = {project: hours for project, hours in zip(projects, hours)}
>>> res
... {'A': 1, 'B': 2, 'C': 3}
My answer is {'A': 1, 'C': 3, 'B': 2}, but I want it to be exactly {'A': 1, 'B': 2, 'C': 3}. I used "sorted", but it only printed out "A, B, C", which missed the value of dictionary