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']
Related
I'm quite new in python coding and I canĀ“t solve the following problem:
I have a list with trackingpoints for different animals(ID,date,time,lat,lon) given in strings:
aList = [[id,date,time,lat,lon],
[id2,date,time,lat,lon],
[...]]
The txt file is very big and the IDs(a unique animal) is occuring multiple times:
i.e:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421],
['25','20-05-13','15:18:15','34.89932','24.13421'],
[...]]
What I'm trying to do is order the ID's in dictionaries so each unique ID will be the key and all the dates, times, latitudes and longitudes will be the values. Then I would like to write each individual ID to a new txt file so all the values for a specific ID are in one txt file. The output should look like this:
{'25':['20-05-13','15:16:17','34.89932','24.09421'],
['20-05-13','15:18:15','34.89932','24.13421'],
[...],
'24':['20-05-13','15:16:18','35.89932','23.09421'],
[...]
}
I have tried the following (and a lot of other solutions which didn't work):
items = {}
for line in aList:
key,value = lines[0],lines[1:]
items[key] = value
Which results in a key with the last value in the list forthat particular key :
{'25':['20-05-13','15:18:15','34.89932','24.13421'],
'24':['20-05-13','15:16:18','35.89932','23.09421']}
How can I loop through my list and assign the same IDs to the same key and all the corresponding values?
Is there any simple solution to this? Other "easier to implement" solutions are welcome!
I hope it makes sense :)
Try adding all the lists that match to the same ID as list of lists:
aList = [['25','20-05-13','15:16:17','34.89932','24.09421'],
['24','20-05-13','15:16:18','35.89932','23.09421'],
['25','20-05-13','15:18:15','34.89932','24.13421'],
]
items = {}
for line in aList:
key,value = line[0],line[1:]
if key in items:
items[key].append(value)
else:
items[key] = [value]
print items
OUTPUT:
{'24': [['20-05-13', '15:16:18', '35.89932', '23.09421']], '25': [['20-05-13', '15:16:17', '34.89932', '24.09421'], ['20-05-13', '15:18:15', '34.89932', '24.13421']]}
I had a huge registration table with 112 fields. For a particular search I want to compare 17 fields & assign colors to variable say 'clrSelected'.
My code is :
reg = Regisration.objects.filter('some condition').order_by("name")
for r in reg:
if r.name=='abc': clrSelected='#fff'
if r.type=='1': clrSelected='#000'
if r.appl=='10': clrSelected='#c1ff51'
if r.code=='': clrSelected='#60c5f7'
if r.qlty=='first': clrSelected='#f99334'
...
...
there will be only one if condition, which need to be colored. Which means the field(from the dictionary) to be compared will change based on the user selection.
I want to access the field name from a dictionary like this
flds = {'1':'name', '2':'type', '3':'appl', '4':'code', '5':'qlty',...}
And use it something like this
if r.flds['1']=='abc': clrSelected='#fff'
How could i use the fields as above. I am using django 1.4 & python 2.7
Just to answer the question, you could use getattr:
if getattr(r, flds['1']) == 'abc': clrSelected = '#fff'
However, I am pretty sure that you could go with a different kind of implementation in this case which doesn't require using a dict like this.
I would suggest using a three tuple list: (fieldName, value, color)
some_list = [('name', 'abc', '#fff'), ('type', '1', '#000'), ...]
And, then use this list to determine the color:
for fieldName, value, color in some_list:
if getattr(r, fieldName) == value:
clrSelected = color
Looking at your implementation, it seems the color will be based on the last if condition which matches. If that is the case, you could create some_list in reverse order and break on the first matching condition.
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
I am new to the whole python thing. I have a question and will try to keep it short.
I am trying to write a program where I have a group of items as below.
product_lookup = {"C1557E" : "FM51", "C1557E" : "JBC4343" "C1565ECA/2" : "FM349",
"C1568E" : "FM133", "C1578E" : "FM154"}
Now I have a enquiry (list of values) as below that I want to cross referance with the dictionary
enquiry_lookup = ["FM51", "FM133", "FM154", "GRE4534"]
Then I" want this displayed as
result ["FM51" : "C1557E", "FM133" : "C1568E", "FM154" : "C1578E", "GRE4534" : "NOT AVAILABLE"]
Firstly, is it possible?
I am stick... HELP PLEASE :)
Only just started and after working on a few things I am getting the feeling it might not be possible??
Please point me in the right direction.
Thanks a stack
G
This might give you a clue:
>>> dict = {"a" : "b", "c" : "d"}
>>>
>>> for k,v in dict.iteritems():
... print k
... print v
...
a
b
c
d
By using iteritems(), we iterate over all key,value pairs in our dictionary. So you can inspect the value to see if it is the value you are looking for, if so you can place the key and the value in your result dictionary.
But, if you are interested in a set of items, and those items are the values instead of the keys of your dictionary, are you sure your dictionary is not backwards? By which I mean, could your dictionary instead be
product_lookup = {"FM51" : "C1557E", etc}
then when you have
enquiry_lookup = ["FM51", etc
you can just see if product_lookup["FM51"] exists? This could be more efficient/easier to write.
I'm trying to use numbers as my dict key. Is there anyway to initiate the dictionary using dict() method?
This works
mydict = { '100':'hundred', '200':'two hundred'}
This doesn't work?
mydict = dict( 100='hundred' )
The error says 'keyword can't be an expression' and I couldn't find any solution.
Thank you.
I can't understand your question exactly, but you mentioned to use number as dict key right? you just directly initiate it using integer instead string like this..
a = {1:'one',100:'hundered'}
print a
{1: 'one', 100: 'hundrered'}
No, it mist be a valid python identifier, so it cannot start with a number.
You can read where i found it at here in the part about dict
https://docs.python.org/2/library/stdtypes.html#typesmapping
Like the comment above says you can use an int, since dictionaries just hash the string and you get an int anyways, in the case of an int it just hashes to itself. But it doesnt work with dict ()
On that page it shows you can do
mydict = dict (zip ([1], ["one"]))
Which is kinda ugly imo, but seems to get the job done
To use the dict method you need to feed it a list or tuple of lists or tuples.
>>> dict([(100, 'hundred'), (200, 'two hundred')])
{200: 'two hundred', 100: 'hundred'}