I am new to programming and currently learning python. I am stuck when trying out dictionaries in python.
I have a normal dict with a key and the value as an empty string:
dict = {'Project_path':''},
'Target_files':'',
'default_ws':''}
I am updating the value of keys like this:
dict['project_path'] = 'Pass'
But I want to create a dict where I don't have to use long keys; instead I can map these keys to numbers so that if i want to update a dict i can do it like this:
dict = {1:{'Project_path':''},
2:{'Target_files':''},
3:{'default_ws':''}}
dict['1'] = 'pass'
It should update the value for 'project_path' as 'pass'
And after updating the values, I have to write this in a file
Is there way to do it ?
Welcome to Programming in Python! Few things here: First, using dict as a variable name is not a good idea, as this is a keyword for the whole class of dictionary objects. You can use something like, my_dict, or something like that.
Second, when you make the keys numbers and then call dict['1'] = 'pass' this looks for the string '1' in the keys, when you have declared the integer 1 as the key. Let me explain:
'1' is a string
1 is an integer.
In python these are two very different things and cannot be mixed around . That's why the value doesn't update. If you were to say dict[1] = 'pass', that should work for you and it should update the values. Note, though that this will overwrite the whole dictionary that is the current value and replace it with 'pass', if instead you just want to change the dictionary key, use
dict[1]['Project_path'] = 'pass'.
This, however seems redundant to me. It's kind of unclear exactly why you want to map integers in there (perhaps to loop through it and change values), but if you just want integers associated with it, you could just create and array of dictionaries like this:
my_array = [{"Project_path": ''}, {"Target_files":''}, {default_ws":''}]
Then, you could access them by their index starting at 0. my_array[0] is {"Project_path":''}. Again, it's kind of unclear why you want to map integers to these dicts, so it doesn't really make sense to me because this is a little redundant.
Finally, writing to a file. There's a lot of webpages out there, because there are many options when it comes to reading and writing files (like this one), but here's the short version.
with open('your_filepath.txt', 'w') as file: #note this will overwrite the current file, see the page I linked.
file.write(my_array[0]) #or whatever you want to write to it.
It's that simple, but like I said, take a look at that page to see what all your options are and choose the best one for you. Hopefully that is helpful and can get you started.
Related
Currently am trying to make code which can pick out either specific or aggregate values for certain actions. I am using a nested dictionary for this, but am having issues calling specific values of nested dictionary. The code runs, but always brings the same value, not matter which key I originally tried to call
I have tried to have it print a variable set to the value of the key in the dictionary. I have also tried to use v.get() to retrieve the value from the dictionary.
properties={'lake':{'repairs':9001,'upgrades':3,'police investigations':69}
,'meadow':{'repairs':3,'upgrades':8}
,'beach':{'repairs':4,'upgrades':2}
,'country':{'repairs':5,'upgrades':54}}
choice=raw_input('Do you want to learn about a specific property or total actions? (type specific or total) ')
choice=choice.lower()
if choice[0]=='s':
for k,v in properties.items():
print(properties.keys())
properti=raw_input('Which property would you like to look at? (enter nothing to exit) ')
print properties[properti]
action=raw_input('What action is it you want to learn about? ')
result=v[action]
print('The '+properti+' property has had '+str(result)+' '+action+' completed.')
I expect when I call for a specific property, choose lake, then choose repairs, that I'd get the 9001. Or even going for meadow, I'd get 3 repairs. Currently I am always getting the country property's amounts for both repairs and upgrades.
Change the following
result=v[action]
to
result=properties[properti][action]
Trying to figure out the right way to parse key-value pairs produced by a Cypher query:
#app.route('/about')
def about():
data = graph.run("MATCH (n) RETURN n.level")
for record in data:
return render_template("output.html",output=record)
Please disregard the fact that I'm not combining the returned records into a list prior to populating the template. I do get one record as output, and am ok with that for now.
What I'm struggling with is - how do I handle the resulting k/v pair
(u'n.level': u'high')
I mean, if I'm just interested in the value 'high', is there a clean way to get hold of it?
Sorry if this sounds too basic. I do understand, there must be some parsing tools, but at this point, I just don't know where to look.
Sorry, the solution is simple. Flask returns a py2neo.database.record object, which can be indexed just like a list, the only caveat being that the list has only one element (not two, as it might appear).
So, if variable record above equals to (u'n.level': u'high'), record[0] will be equal to 'high'.
And the 'u's can be just ignored altogether, as explained elsewhere on SO.
my first question, be gentle :-)
I have a rails application using pieces of text from a database (table basically contains a short key k and the corresponding text; sort of like i18n, but for reasons out of scope here I don't want to use that right now). Made a small helper function for the views to get the matching text by key, along the lines of "Text.find_by k: x". Hell of a database load but allowing the texts to be changed dynamically by a CMS.
But since it turned out that the texts do rarely change, I wanted to preload the whole table into a hash instead. Since I'm not sure where to put such initialization stuff, and also because I thought lazy loading might be cool, here is what I did (simplified):
module MainHelper
...
##items = nil
def getText(x)
initItems if !##items
##items[x]
end
private
def initItems
##items = {}
Text.all.each {|t| ##items[t.k] = t.text} #load from model
end
Which seems to work great. But since I am quite a newbie here, I wonder if anybody thinks there is a better solution, or a solution that is more "the rails way"? Any comments highly appreciated!
What you've done is pretty cool. I'd be more likely to make a method items that memoizes the items, as opposed to an explicit initItems method. That would be the more conventional solution.
Use pluck to get only the fields in the table that you need... it'll make the SQL call more efficient.
because pluck in this case returns an array of two-element arrays, it's easy to use the to_h method to convert it into a hash.
(also, convention is to use snake_case for method names)
module MainHelper
...
##items = nil
def get_text(x)
items[x]
end
private
def items
##items ||= Text.pluck(:k,:text).to_h #load from model
end
end
This question already has answers here:
Django: __in query lookup doesn't maintain the order in queryset
(6 answers)
Closed 8 years ago.
I've searched online and could only find one blog that seemed like a hackish attempt to keep the order of a query list. I was hoping to query using the ORM with a list of strings, but doing it that way does not keep the order of the list.
From what I understand bulk_query only works if you have the id's of the items you want to query.
Can anybody recommend an ideal way of querying by a list of strings and making sure the objects are kept in their proper order?
So in a perfect world I would be able to query a set of objects by doing something like this...
Entry.objects.filter(id__in=['list', 'of', 'strings'])
However, they do not keep order, so string could be before list etc...
The only work around I see, and I may just be tired or this may be perfectly acceptable I'm not sure is doing this...
for i in listOfStrings:
object = Object.objects.get(title=str(i))
myIterableCorrectOrderedList.append(object)
Thank you,
The problem with your solution is that it does a separate database query for each item.
This answer gives the right solution if you're using ids: use in_bulk to create a map between ids and items, and then reorder them as you wish.
If you're not using ids, you can just create the mapping yourself:
values = ['list', 'of', 'strings']
# one database query
entries = Entry.objects.filter(field__in=values)
# one trip through the list to create the mapping
entry_map = {entry.field: entry for entry in entries}
# one more trip through the list to build the ordered entries
ordered_entries = [entry_map[value] for value in values]
(You could save yourself a line by using index, as in this example, but since index is O(n) the performance will not be good for long lists.)
Remember that ultimately this is all done to a database; these operations get translated down to SQL somewhere.
Your Django query loosely translated into SQL would be something like:
SELECT * FROM entry_table e WHERE e.title IN ("list", "of", "strings");
So, in a way, your question is equivalent to asking how to ORDER BY the order something was specified in a WHERE clause. (Needless to say, I hope, this is a confusing request to write in SQL -- NOT the way it was designed to be used.)
You can do this in a couple of ways, as documented in some other answers on StackOverflow [1] [2]. However, as you can see, both rely on adding (temporary) information to the database in order to sort the selection.
Really, this should suggest the correct answer: the information you are sorting on should be in your database. Or, back in high-level Django-land, it should be in your models. Consider revising your models to save a timestamp or an ordering when the user adds favorites, if that's what you want to preserve.
Otherwise, you're stuck with one of the solutions that either grabs the unordered data from the db then "fixes" it in Python, or constructing your own SQL query and implementing your own ugly hack from one of the solutions I linked (don't do this).
tl;dr The "right" answer is to keep the sort order in the database; the "quick fix" is to massage the unsorted data from the database to your liking in Python.
EDIT: Apparently MySQL has some weird feature that will let you do this, if that happens to be your backend.
Excuse me for the basic question but I come from a PHP background and made use of multidimensional arrays to transfer information around.
What is the best alternative in Python?
$person[1]['name'] = 'bob'
$person[1]['age'] = 27
$person[1]['email'] = 'aaa#aa.com'
What I'm trying to is prepare an array to send to a template, I need to get a list of persons and then calculate when their next meeting/visit should be. I then want to send an array to the template like:
Name Last Meeting Date Next Meeting Date
Bob 01/04/2012 01/05/2015
The Next meeting date is calculated based on many variables so I just want to prepare the array in the view and then pass it to the template.
person = [{'name':'bob', 'age':27, 'email':'aaa#aa.com'}, {...}, {...}]
though if you use django, you might want to check the documentation and how models (user model for instance) work, cause you won't need to declare a list of dicts...
In Python we have different kinds of data structures, you can't just append data like in the example you show. What you need in this specific case is a list (which is an equivalent of a 1-dimensional array) filled with dicts (just as an array of key-value pairs) where you can define your data:
people = [{"name": "Bob", "last_meeting": yesterday, "next_meeting": tomorrow}, {...}, ...]
Check this link for more info on data structures in python: http://docs.python.org/2/tutorial/datastructures.html
Though, #nnaelle is right, if you are using django and not just python, you should check out how the framework manages requests using Forms, Models, Querysets, views and all the useful stuff that powers Django: https://docs.djangoproject.com/en/1.5/
That will for sure ease a lot of your work ;)
Good luck!