implement dynamic nested dictionaries? [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
mother_dict=
{'son_dict':{'Name':'Jason','Age':26},'daughter_dict':{'Name':'Emma','Age':19}}
father_dict={}
father_dict['Child']=mother_dict[son_dict]
I need a way to replace father_dict['Child'] with a dictionary from mother_dict based on input.
I've tried deleting the contents of father_dict and replacing them with the contents of mother_dict with .update(), but that of course adds the whole dictionary, I've tried using input() to ask the user for a child, so if they said 'Jason' it would replace 'Child' with son_dict, but when I got into families with ten or so kids there would need to be ten functions, and if the children's names changed then both the functions and the dictionaries would need to be re-written. I'm hung up on using input to grab a specific dictionary from mother_dict and copying it to father_dict.

Maybe something like the following?
choice = ''
mother_dict= {'son_dict':{'Name':'Jason','Age':26},'daughter_dict':{'Name':'Emma','Age':19}}
father_dict = {}
while choice not in mother_dict:
choice = raw_input('Which dict do you want? ')
father_dict[choice] = mother_dict[choice]
This code gets input until the input is valid (it is in mother_dict), and then it adds that input to father_dict.

Related

String Operations and Manipulation in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I'm building a scraping spider and I would like some help on how to extract the right information out of each response in Python
response.css(".print-acta-temp::text").get()
'TEMPORADA 2021-2022'
I would like to know how to collect only the 2021-2022. Should I use the str command?
response.css(".print-acta-data::text").get()
'Data: 14-05-2022, 19:00h'
I need to extract only the date into one variable and the time into another variable.
response.css(".print-acta-comp::text").get()
' CADET PRIMERA DIVISIÓ - GRUP 2'
I need to collect the data before the first space, the data collected between the 2 spaces and finally the number into another variable.
response.css(".print-acta-jornada::text").get()
'Jornada 28'
I need to collect the data after the first space.
if you trust the website to produce the data you want exactly followed by 'TEMPORADA ' all the time you can use
tu_string = 'TEMPORADA 2021-2022'
nueva_string = tu_string.replace('TEMPORADA ','')
print (nueva_string)
like, there's regex and all of that, but you can worry about learning that later, tbh.
I need to collect the data before the first space, the data collected
between the 2 spaces and finally the number into another variable.
a simple way to do this is to split
teva_string = 'CADET PRIMERA DIVISIÓ - GRUP 2'
teva_lista = teva_string.split(' ')
print (teva_lista)
Any decision on how to parse a string is going to depend on one's assumptions about what form the strings are going to take. In the particular case of 'TEMPORADA 2021-2022', doing my_string.split(' ')[1] will get the years. 'Data: 14-05-2022, 19:00h'.split(' ') will get the list ['Data: 14-05-2022,, '19:00h'], while 'Data: 14-05-2022, 19:00h'.split('-') will get ['Data: 14-05-2022', ' 19:00h']. You can also use datetime libraries or regular expressions, with the latter allowing for more customization if the form of your data varies.

Python dict, extracting values [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am having trouble to query my database maybe someone could give me a hand.
I am using a django application so I guess Sqlite3 >> and the output I would like to get is the score value
b = Answer.objects.get(id = 23)
which give me an output of :
<Answer: Answer to questionID '4' : AnswerID '23'>
when I do :
b.values
I get a dict in the form :
['{
"1)Long descriptive text":Score,
"2)Long descriptive text":Score,
"3)Long descriptive text":Score,
"4)Long descriptive text":Score
}']
with score beeing an Integer from 0 to 100 so for example "Long descriptive text":85
I need to extract the score using a query but I can't manage to do it
Normaly for a Dict[key:value] I would do a Dict[key] but here I do not know how to do it
could you give me a hand
Thx you very much
This looks suspiciously like Django If so:
so b = Answer.objects.get(id = 23) is not truely that - what you are seeing is the str function of the Answer when you print it off. because you used .get rather then a .filter you get the object rather then a QuerySet (which you can think of as being a list).
Basically, I suspect you shouldn't be using values, but accessing the data... something like
b = Answer.objects.get(id=..)
b.score
or if you wanted to loop over other answers:
answers = Answer.objects.filter(...)
for a in answers:
a.score
for what the .score is, look in your models.py file - look what parameters is has (things looking like score = models.IntegerField() etc, then you would use a.score)

How to find an item in a dict with nested classes? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm a newbie programming in python and I can´t find a element in a complex dict (for me at least).
This dict contains items "FareAttribute" and the same time this class contains elements "FareRule". I want to find the element that matches FareRule.origin_id=="city1" and FareRule.destination_id=="city2".
How I can to find this?
Thanks for any comment in advance. I'm a bit lost
Edit to add dict (output when print first item). The classes belongs to transitfeed library (Google Transit). Right now I can't execute program, I'm out.
{u'AA': <FareAttribute [('currency_type', u'EUR'), ('fare_id', u'AA'), ('payment_method', 0), ('price', 1.5), ('rules', [<FareRule [('contains_id', None), ('destination_id', u'A'), ('fare_id', u'AA'), ('origin_id', u'A'), ('route_id', None)]>]), ('transfer_duration', None), ('transfers', 0)]>,...}
EDIT2 Please try something like this (if python 2.7):
for fare in schedule.GetFareAttributeList():
for rule in fare.GetFareRuleList():
if rule.origin_id == 'B1' and rule.destination_id == 'B1':
print rule

Assigning variable with other variable in python [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey guys am new to python development..I am studying python on my way
I have just tested a simple code which includes assigning two variables with single at one line
Here is my snippet:
name = 1
somevariable = "hellow am new to python"
print somevariable[name]
And i got an output "e".
I did not understand what it means. I just tried out a random example .Is it allowed to do like this in python .or is it with arrays. Please help me to find an appropriate answer. Any help would be appreciated.
EDIt
Can we store a variable information to other variable in python
For eg
name = 1
age = 2
string = "yeah am a man"
name[age] = stringname = 1
My qus is that can we store the value 1 to age ?..AM new to python ..Sorry for the bad question
First of all you need to read basic of python first, because from your snippet clearly says that you don't know what is mutable and immutable object in python.
And for your question,this name[age] = stringname = 1 is not allowed.
First you will name Error for age after that you will get int object is not allowed for item assignment.
About list:
About Dictionary:
I'm not quite sure what you're trying to achieve, but it sounds a bit like you're trying to store multiple attributes (e.g name and age). If so, you could use a dict. e.g.
# initialise the dict
user = {}
# Add some data
user["name"] = "User"
user["age"] = 1
To retrieve the variables, just use e.g. user["name"]

How to add data to a list in the code while running [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Suppose i want to add something to
list = []
such that the value of list gets updated in the code it self.
In runtime:
list gets modified to
list =['hello','Dude']
How can i do so?
What i mean is, that there are real changes made to the List value in the .py file.
Judging from your comments to one of the other answers what you are looking for is a way to serialize and save an object to a file so you can reload it once you re-run the program. This is done using pickle.
An example of this can be found on stack overflow: How to save an object in Python:
import pickle
try:
with open('list.pk', 'rb') as input:
list = pickle.load(input)
except:
list = []
list.append('something')
print(list)
with open('list.pk', 'wb') as output:
pickle.dump(list, output, pickle.HIGHEST_PROTOCOL)
Just use append where ever you need it:
list = []
list.append('hello')
print list
list.append('Dude')
print list
Output:
['hello']
['hello', 'Dude']<
Easy way would be to create additional file and to store variables there.
Code:
list = []
f = open("list.txt", "r+")
for item in f:
list.append(str(item).rstrip())
f.write("Something")
f.close()
list.txt:
hello
Dude
list.txt after execution:
hello
Dude
Something
The only way to do it is rewriting the .py file.
You don't really want to do that even if it's indeed technically possible.
You should instead keep your data in a separate file, loaded when starting the program and saved back when exiting.
There are special modules for storing python values like e.g. shelve.
A very common alternative is storing the data in a format that can be understood even by other languages intead of python objects, e.g. in a relational database like sqlite.

Categories