iterate over multiple lists inside an array in django template - django

I have two things, first is group and 2nd is group-item.
Group list is: [<group1: group>, <group2: group>]
Group Item list is:
[[<obj1: obj>, <obj2: obj>], [<obj3: obj>]]
where first set of objects belong to first group and second set belong to 2nd group.
I want to iterate these lists in Django Template and ouput is required something like this:
Group1
obj1
obj2
Group2
obj3
Any help is appericiated.
Thanks.

This is not a Django type of question certainly, it is python list manipulation type, the list items are Django objects.So, here I am giving example of how to manipulate the two list objects for the required format.
I assume,
Example input:
Instead of these example input list, you can use your django list objects.
list1 = ['Group1','Group2','Group3']
list2 = [['Item1','Item2'],['Item3','Item4'],['Item5']]
Snippet:
import itertools
In [19]: for g,i in itertools.izip_longest(list1,list2):
....: print "Group:",g
....: print "Items:",i
....:
Group: Group1
Items: ['Item1', 'Item2']
Group: Group2
Items: ['Item3', 'Item4']
Group: Group3
Items: ['Item5']
Refer these:
zip and izip_longest

Related

python how to compare elements in a dictionary?

I have a python dictionary like :
pydict = {"group1":[{"name":"john","count":1},{"name":"johny","count":2}],
"group2":[{"name":"raj","count":1},{"name":"johny","count":4}],
"group3":[{"name":"ram","count":1},{"name":"raj","count":4}]
}
I want to iterate through pydict and i want to maintain a table like below:
Name group1 group2 group3
johny true true
raj true true
I tried using python sets so the each keys elements in pydict can be assigned to sets and finally do intersection but it is not helping.
Please suggest me a fastest way to do this.
A really naive implementation of this would be to just make another dict based on names:
from collections import defaultdict
names = defaultdict(set)
for group in sorted(pydict.keys()):
for person in pydict[group]:
names[person["name"]].add(group)
for key, val in names.iteritems():
print key, ":", list(val)
Output
johny : ['group1', 'group2']
john : ['group1']
raj : ['group3', 'group2']
ram : ['group3']

Add values from a list of dictionaries to separate lists and find/count common values

I have a list containing dictionaries like this:
[{"abc":"da123-tap","efg":"xyzf","acd":"123-brf"}, {"abc":"ab234-tap","efg":"yuvi","acd":"345-brf"}]
I want all the values of abc in a list (list1) and all the values of efg in another list (list2).
Update to question:
I read a file to get this list of dictionaries:
[{"Sample":"da123-tap","Name":"john","dof":"Date(304239600000)","Account":"Clinic1"},
{"Sample":"da456-tap-tap","Name":"smith","dof":"Date(304239600000)","Account":"Clinic2"},
{"Sample":"da678-tap-tap","Name":"jane","dof":"Date(304239600000)","Account":"Clinic1"},
{"Sample":"da987-tap-tap","Name":"doe","dof":"Date(304239600000)","Account":"Clinic2"}]
Find:
Values from Sample in list1
Values from Account in list2
Count values of Sample that belong to Clinic1
Count values of Sample that belong to Clinic2
Only for educational reasons, the elegant way to direct values of different keys into multiple lists could be to use zip() and unpacking:
>>> l = [
... {"abc":"da123-tap","efg":"xyzf","acd":"123-brf"},
... {"abc":"ab234-tap","efg":"yuvi","acd":"345-brf"}
... ]
>>>
>>> a, b = zip(*[(item["abc"], item["efg"]) for item in l])
>>> print(a)
('da123-tap', 'ab234-tap')
>>> print(b)
('xyzf', 'yuvi')

List output formatting in a variable

I made a Email Bot that crawls Craigslist and emails me when an item meets my queries. I am at the final stage and have everything working but my email format.
What I have is a loop that appends Craigslist Listings to a list. Outside my loop I add the List to my email Def as an argument.
Example of what I need:
list = ['item1', 'item2', 'item3']
print list
['item1', 'item2', 'item3'] # I don't want it on a single line
for i in list:
print i
item1
item2
item3
#I want a variable with the single line item format.
I want the single line format placed into a Variable rather than as the list. My list could be 1 item or 20, depends on what has been posted on Craigslist.
Any help would be great.
With str.join you can join a list by the string given:
"\n".join(my_list)
If you need more fancy formatting than a string per line you should look at a combination of join and str.format
P.S.: By the way, don't shadow the "list" builtin, that's bad practice. It will lead to errors whenever you want to use the builtin.
Not entirely clear what you are asking. As I understand the question, you want to print the list items on different lines, but in the same style as used when printing the list in one line.
The __str__ method of a container class usually uses the __repr__ method of the contained objects, so if you want to print the items on several lines in the same style as when you print it in one line, use the repr function to get the result of __repr__.
>>> lst = ['item1', 'item2', 'item3']
>>> for i in lst:
... print repr(i)
...
'item1'
'item2'
'item3'

Isolating the elements of a row in python

I am working on a project where i am trying to plot the rainfall pattern of various states of my country. By using this command i fetch the data from my database:
cur.execute('SELECT JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DECEMBER FROM Rainfall_In_Cm where STATE_UT = %s && DISTRICT = %s' ,(state , district))
The result comes in the form of a list with 1 element(the 1 row from the query output) :
(Decimal('17.5'), Decimal('9.9'), Decimal('8.9'), Decimal('4.0'), Decimal('9.3'), Decimal('53.8'), Decimal('227.1'), Decimal('280.90'), Decimal('125.4'), Decimal('28.1'), Decimal('5.0'), Decimal('4.7'))
Now i want all the elements to be in form of a list that i can use with matplotlib to plot a graph and I want to remove 'Decimal' string from infront of every value . How can i do it?
Your result is a tuple, not a list, but that is not a problem.
Casting should work for these Decimal objects. You can use a list comprehension:
#Data from your example
foo = (Decimal('17.5'), Decimal('9.9'), Decimal('8.9'), Decimal('4.0'), Decimal('9.3'), Decimal('53.8'), Decimal('227.1'), Decimal('280.90'), Decimal('125.4'), Decimal('28.1'), Decimal('5.0'), Decimal('4.7'))
bar = [float(i) for i in foo]
If you want to have rather integers, use:
bar = [int(i) for i in foo]

Python 2.7 - Iterating Over Elements in 2 Different Lists, Why Each One Print Different Format

In my newbie experimenting and trying to write lots of little scripts and learn; I bumped into this puzzlement:
import re
nouns = ['bacon', 'cheese', 'eggs', 'milk']
article = []
def list_in_list(list1, list2):
for list_1_element in list1:
print list_1_element
for list_2_element in list2:
print list_2_element
with open('test_sentence.txt', 'r') as input_f:
for line in input_f:
article.append(re.findall(r"[\w']+|[.,!?;:]", line))
list_in_list(article, nouns)
Here is the contents of the test_sentence.txt:
I need to go shopping today and some of the things I need to buy are bacon, cheese and eggs. I also need to buy something with a comma in it, such as milk, cheese, and bacon.
What I don't understand is why print list_1_element actually prints the whole 'list1' list such as ['I', 'need', 'to', 'go'.............]. And the the print list_2_element actually prints each element of that list on a new line, as I would expect.
So why the difference?
article.append([some list]) appends the list as one item
article.extend([some list]) would append each item in some list to the article list
Because article is a list containing a single item. You add one list of lists per line, and you have one line.