how to add data to list of dictionaries in Django - django

I want to add data to list of dictionaries
a =[100, 200, 300]
b =['apple', 'orange', 'grapes']
c=[]
for val in a:
c.append({'price':val})
for val in b:
c.append({'fruit':val})
print(c)
result should be like this:
[
{'price':100, 'fruit':'apple'}, {'price':200, 'fruit':'orange'}, {'price':300, 'fruit':'grapes'}

You can work with list comprehension:
a = [100, 200, 300]
b = ['apple', 'orange', 'grapes']
c = [{'price': p, 'fruit': f} for p, f in zip(a, b)]

Related

Iterating through multiple lists in Django templates

views.py
def exa(request):
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7]
list3 = [True, False, False]
context = {
'l1' : list1,
'l2' : list2,
'l3' : list3,
}
return render(request, 'patient_registration/111.html', context)
template
{%for a, b in zip(l1, l2)%}
{{a}}
{{b}}
{%endfor%}
template can be not show any list
i want to display multipe list thorugh context in template
You can use zip in your view:
mylist = zip(list1, list2, list3)
context = {
'mylist': mylist
}
and in your template use:
{% for item1, item2, item3 in mylist %}
to iterate through your lists.

Python Group by first item in list and return Keys

I am able to group a list by its first item but I cannot figure out how to return the unique keys.
from itertools import groupby
List = [['Hello','Sam',27,5],['Hello','Mark',22,4],['Goodby','Steven',86,34]]
keys = []
glist = [list(item[1])for item in groupby(sorted(List), key=lambda x: x[0])]
Is this what you are looking for?
from itertools import groupby
lst = [['Hello','Sam',27,5],['Hello','Mark',22,4],['Goodby','Steven',86,34]]
for key, group in groupby(lst, key = lambda x: x[0]):
print(key + " :", list(group))
#output:
Hello : [['Hello', 'Sam', 27, 5], ['Hello', 'Mark', 22, 4]]
Goodby : [['Goodby', 'Steven', 86, 34]]

How to insert randomly an element into a List

Given a List[Int] l, how can I insert randomly a new element elem into the List[Int] l?
def randomInsert(l: List[Int], elem: Int): List[Int] = ???
This can be done by first, picking a random index into the list and then inserting the new element at that index. Also this can be done in a generic way:
import scala.util.Random
def randomInsert[A](l: List[A], elem: A): List[A] = {
val random = new Random
val randomIndex = random.nextInt(l.length + 1)
l.patch(randomIndex, List(elem), 0)
}
Usage:
scala>randomInsert(List(1,2,3,4,5),100)
res2: List[Int] = List(1, 2, 3, 4, 5, 100)
scala>randomInsert(List(1,2,3,4,5),100)
res3: List[Int] = List(100, 1, 2, 3, 4, 5)
scala>randomInsert(List(1,2,3,4,5),100)
res4: List[Int] = List(1, 2, 100, 3, 4, 5)
We can use this method to add recursively several elements:
import scala.util.Random
import scala.annotation.tailrec
def randomInsert[A](l: List[A], elem: A, elems: A*): List[A] = {
val random = new Random
#tailrec
def loop(elemToInsert: List[A], acc: List[A]): List[A] =
elemToInsert match {
case Nil => acc
case head :: tail =>
val randomIndex = random.nextInt(acc.length + 1)
loop(tail, acc.patch(randomIndex, List(head), 0))
}
loop(elem :: elems.toList, l)
}
Usage:
scala>randomInsert(List(1,2,3,4,5),100,101,102)
res10: List[Int] = List(1, 2, 101, 3, 4, 5, 100, 102)
scala>randomInsert(List(1,2,3,4,5),100,101,102)
res11: List[Int] = List(1, 2, 102, 100, 101, 3, 4, 5)
scala>randomInsert(List(1,2,3,4,5),100,101,102)
res12: List[Int] = List(1, 2, 3, 4, 100, 5, 102, 101)
Edit:
As per comment, an more efficient way to do this is to join both list and to shuffle the combined one - note than by doing so you may lose the original order of the list:
import scala.util.Random
def randomInsert[A](l: List[A], elem: A, elems: A*): List[A] = {
Random.shuffle((elem :: elems.toList) reverse_::: l)
}

How to get an index of a list element in elixir?

I have
>> list = ["a","b","c"]
and I need to get the index of the elements and create a new list that follows
>> list_2 = [[1,"a"], [2,"b"], [3,c]]
to create the new list I used
lista = Enum.flat_map(list, fn x -> [index,x] end)
but I can't find a function like to get the "index" value
list = ["a","b","c"]
list_2 = Enum.with_index(list)
gives
[{"a", 0}, {"b", 1}, {"c", 2}]
Enum.zip/2 is your friend here.
list = ~w[a b c]
#⇒ ["a", "b", "c"]
list_2 = Enum.zip(1..3, list)
#⇒ [{1, "a"}, {2, "b"}, {3, "c"}]
or, if the size is unknown upfront, you might
Enum.zip(Stream.iterate(1, & &1 + 1), list)
#⇒ [{1, "a"}, {2, "b"}, {3, "c"}]
to get a lists, not tuples, simply map the result
1
|> Stream.iterate(& &1+1)
|> Enum.zip(list)
|> Enum.map(&Tuple.to_list/1)
#⇒ [[1, "a"], [2, "b"], [3, "c"]]
Another way would be to use Enum.with_index/1
list
|> Enum.with_index(1)
|> Enum.map(fn {e, i} -> [i, e] end)
#⇒ [[1, "a"], [2, "b"], [3, "c"]]
I know the below answer is not related to asked question, but I'm sure it will help some in the feature.
In my case, I have to add an index to an array of lists/map.
So I did the below:
formatted_list = [%{"map 1": 1}, %{"map 2": 2}]
list_with_index = formatted_list
|> Enum.with_index(1)
|> Enum.map(fn {e, i} -> Map.put(e, :index, i) end)
Result:
[
{
"index": 1,
"map 1": 1
},
{
"index": 2,
"map 2": 2
}
]

How to count elements from list if specific key present in list using scala?

I have following list structure -
"disks" : [
{
"name" : "A",
"memberNo" :1
},
{
"name" : "B",
"memberNo" :2
},
{
"name" : "C",
"memberNo" :3
},
{
"name" : "D",
}
]
I have many elements in list and want to check for 'memberNo', if it exists
I want count of from list elements.
e.g. here count will be 3
How do I check if key exists and get count of elements from list using scala??
First create class to represent your input data
case class Disk (name : String, memberNo : String)
Next load data from repository (or other datasource)
val disks: List[Disk] = ...
And finally count
disks.count(d => Option(d.memberNo).isDefined)
In a similar fashion as in #SergeyLagutin answer, consider this case class
case class Disk (name: String, memberNo: Option[Int] = None)
where missing memberNo are defaulted with None; and this list,
val disks = List( Disk("A", Some(1)),
Disk("B", Some(2)),
Disk("C", Some(3)),
Disk("D"))
Then with flatMap we can filter out those disks with some memberNo, as follows,
disks.flatMap(_.memberNo)
res: List[Int] = List(1, 2, 3)
Namely, for the counting,
disks.flatMap(_.memberNo).size
res: Int = 3
Likewise, with a for comprehension,
for (d <- disks ; m <- d.memberNo) yield m
res: List[Int] = List(1, 2, 3)