How to save 'arrays' to variable from QueryDict - python

I have a following structure of QueryDict:
QueryDict: {u'tab[1][val1]': [u'val1'], u'tab[1][val2]': [u'val2'], u'tab[0][val1]': [u'val1'], u'tab[1][val2]': [u'val2']}
I want to store it in an iterable variable so I can do something like this:
for x in xs:
do_something(x.get('val1'))
where x is tab[0] etc
I tried:
dict(request.POST._iteritems())
but it doesn't return tab[0] but tab[0][val1] as an element.
Is it possible to store entire tab[idx] in variable?

Django's QueryDict has a few additional methods to deal with multiple values per key compared to the traditional dict; useful for your purposes are:
QueryDict.iterlists() Like QueryDict.iteritems() except it includes
all values, as a list, for each member of the dictionary.
QueryDict.getlist(key, default)
Returns the data with the requested key, as a Python list. Returns an empty list if the key doesn’t exist and no default value was provided. It’s guaranteed to return a list of some sort unless the default value was no list.
QueryDict.lists()
Like items(), except it includes all values, as a list, for each member of the dictionary.
So you can do something like:
qd = QueryDict(...)
for values in qd.lists():
for value in values:
do_something(value)
Also note that the "normal" dict methods like get always return only a single value (the last value for that key).

Related

How to check if a tuple key is in a dict with O(1) time?

I'm trying to implement a hash table/hash map in Python.
Say I'm using tuples as keys like this:
hashTable = {}
node = [1, 2, 3]
print(hashTable[tuple(node)]) # throws an error
hashTable[tuple(node)] = True
print(hashTable[tuple(node)]) # prints TRUE
I want to check if elements exist in the hashTable before adding it. I have tried initializing the dictionary with all False values.
hashTable = {}
for i in range(1000):
hashTable[i] = False
So this creates a hash table of size 1000 with every slot set to FALSE. But if I try to check if a non-existent element is in the hashTable:
print(hashTable[tuple(node)])
I get the same error as before.
How does one go about doing this? I think this would work iterating through the dict with in but doesn't that defeat the whole purpose of using a hash table in the first place?
Accessing a key is similar to, but not necessarily the same as checking if it exists. To check if a key is in a dictionary, use dict.__contains__ via the in operator. To check if it is missing, use the not in operator:
key = tuple(node)
if key not in hashTable:
hashTable[key] = value
That being said, a totally valid way to check for containment can be by attempting access:
key = tuple(node)
try:
# attempt to use hashTable[key]
except KeyError:
# Do something with missing key
The advantage of doing it this way when both paths are needed is that you only need to access the dictionary once rather than twice.
Try to avoid calling tuple(node) over and over: it's not free. If you can, generate node as a tuple, do so. If not, perform the conversion once and use the converted value.
You can use the in operator to determine membership in a dictionary:
e.g.
if tuple(node) in hashTable:
x = hashTable[tuple(node)]
...
You can try to get the key and in case it is not in de dictionary yet, return a default value as may be None:
x = hashTable.get(node, default=None)

Update dictionary and create key-value pairs with loop values

i'm trying to append to a dictionary. there are two loops. the name of the keys depends on the value of the inner loop and the key is the value of a variable which is updated within the loop. my script is
def append_value(dict_obj, key, value):
# Check if key exist in dict or not
if key in dict_obj:
# Key exist in dict.
# Check if type of value of key is list or not
if not isinstance(dict_obj[key], list):
# If type is not list then make it list
dict_obj[key] = [dict_obj[key]]
# Append the value in list
dict_obj[key].append(value)
else:
# As key is not in dict,
# so, add key-value pair
dict_obj[key] = value
for x in range(tot):
dict=['output'=x]
for a in range(33,91):
index_val=(a*sum_t)/x
# now i'm trying to create key names that would be year_33 year_34 and so on
head=''
head='year_{}'.format(a)
append_value(dict, head=avg_PMI)
i get the error name 'append_value' is not defined. would appreciate any help. i would like to loop over values of tot and the (33,91) range. each combination of the two gives a unique values and i want to create a dictionary which will become a csv where x values are rows, a is the column.
thanks!
edited: to show append_value function
The cause of the error is that when you call a function with head=avg_PMI, python assumes that head is an argument. For append_value, the only arguments are dict_obj, key and value. I assume that you want to add a value to the dictionary such that head=avg_PMI. To do this, you have to call the function append_value in the following way:
append_value(dict, head, avg_PMI).

Modify multiple keys of dictionary by a mapping dictionary

I have 2 dict, one original and one for mapping the original one's key to another value simultaneously,for instance:
original dict:
built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}},
'Germany':{'ajax-amsterdam-youth':{'lance':'test2'}}}
mapping dict:
club_team_dict={'deportivo-cuenca-u20':'deportivo','ajax-amsterdam-youth':'ajax'}
It works well if I use the following code to change the key of the nested dict of original dict,like
def club2team(built_dict,club_team_dict):
for row in built_dict:
# print test_dict[row]
for sub_row in built_dict[row]:
for key in club_team_dict:
# the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it
if sub_row==key:
built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row)
return built_dict
and the result:
{'Germany': {'ajax': {'lance': 'test2'}}, 'China': {'deportivo': {'danny': 'test1'}}}
so far so good, however if I have a dict with multiple key mapping to the same key,for example,my original dict is like
built_dict={'China':{'deportivo-cuenca-u20':{'danny':'test1'}},
'Germany':{'ajax-amsterdam-youth':{'lance':'test2'},
'ajax-amsterdam':{'tony':'test3'}}}
and the mapping dict with more then 1 key mapping to the same value,like:
club_team_dict={'deportivo-cuenca-u20':'deportivo',
'ajax-amsterdam-youth':'ajax',
'ajax-amsterdam':'ajax'}
as you can see, both 'ajax-amsterdam-youth'and 'ajax-amsterdam-youth' are mapping to 'ajax',and the trouble is when I use the same code to execute it, the original dict's size has been changed during the iteration
RuntimeError: dictionary changed size during iteration
I want to get a result with nested list for the same key like this
{'Germany': {'ajax':[{'lance': 'test2'},
{'tony' : 'test3'}]}},
'China': {'deportivo': [{'danny': 'test1'}]}}
Well I have found a solution for this,the code:
def club2team(built_dict,club_team_dict):
for row in built_dict:
# print test_dict[row]
for sub_row in built_dict[row].keys():
for key in club_team_dict:
# the key of club_team_dict must be a subset of test_dict,or you have to check it and then replace it
if sub_row==key:
# built_dict[row][club_team_dict[sub_row]] = built_dict[row].pop(sub_row)
built_dict[row].setdefault(club_team_dict[sub_row],[]).append(built_dict[row].pop(sub_row))
return built_dict
pay attention to the for sub_row in built_dict[row].keys(): and setdefault() method, I used to believe that in python 2.7, the default iteration for dict is just iterate the keys(), however, this time it proves it's a little different, maybe you have better solution, please show me and it will be appreciate,thank you

python call function in get method of dictionary instead default value

Need some help in order to understand some things in Python and get dictionary method.
Let's suppose that we have some list of dictionaries and we need to make some data transformation (e.g. get all names from all dictionaries by key 'name'). Also I what to call some specific function func(data) if key 'name' was not found in specific dict.
def func(data):
# do smth with data that doesn't contain 'name' key in dict
return some_data
def retrieve_data(value):
return ', '.join([v.get('name', func(v)) for v in value])
This approach works rather well, but as far a I can see function func (from retrieve_data) call each time, even key 'name' is present in dictionary.
If you want to avoid calling func if the dictionary contains the value, you can use this:
def retrieve_data(value):
return ', '.join([v['name'] if 'name' in v else func(v) for v in value])
The reason func is called each time in your example is because it gets evaluated before get even gets called.

Updating values in dictionary object

My program has a class Words where a defaultdict(int) named t_e_f is created as an object and a function main() that contains a pointer to a function that uses the values of the dictionary 't_e_f' to compute other calculations. 't_e_f' is a dictionary having as key a tuple of words and as value a float number.
My programs looks like this:
class Words:
def __init__(init):
self.t_e_f=Words.set_t_e_f(self)
def set_t_e_f(self):
raw_text_e=open_file('toyen')
raw_text_f=open_file('toyde')
tokens_e=raw_text_e.split()
tokens_f=raw_text_f.split()+['NULL']
tef_dict=collections.defaultdict(int)
for word_e in tokens_e_set:
for word_f in tokens_f_set:
tef_dict[(word_e,word_f)]=1/len(tokens_e_set)
return tef_dict
def get_t_e_f(self):
return self.t_e_f
def main():
words=Words()
t_e_f=words.get_t_e_f()
s_total_e=normalization(t_e_f)
I then have a normalization function that takes t_e_f and uses it to compute calculations over the values of another dictionary created in the normalization function, s_total_e.
def normalization(t_e_f):
s_total_e=collections.defaultdict(int)
words_sent_e=['the','big','book']
words_sent_de=['das','grosse','buch']
for item in words_sent_e:
s_total_e[item]
for item in words_sent_e:
for item_2 in words_sent_de:
s_total_e[item]+=t_e_f[(item,item_2)]
The problem is that when t_e_f is passed to normalization all the values are set to 0, therefore losing the initial values set when the words object was created. I was wondering what was happening and how to solve this problem.
Thank you.
The tef_dict variable isn't being saved to the instance and is not being returned. Add a line to set_t_e_f():
return tef_dict
Also note that defaultdict will automatically add a zero entry even if you only lookup or inspect a missing key.
You may be better-off using collections.Counter() instead. Unlike defaultdict, it will return zeros for missing keys but won't add them to the underlying dictionary.

Categories