Python dict, extracting values [closed] - python

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)

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.

I want to print names of employees who have both work number and mobile number.below is my json body [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 2 years ago.
Improve this question
I want to print firstname of employees who have both work number and mobile number. Below is my json body. I am facing difficulty in getting inside phoneNumbers attribute. My final output should be: "Adhi as Adhi has both work and mobile numbers".
I am not able to iterate the inner dictionary of phoneNumbers attribute.Can you please help me on this.
This is my python code
for i in Data['users']:
for j in i['phoneNumbers']:
for i in range(len(j)):
if j['type']=="work" and j['type']=="mobile":
print("Firstname",i['firstName'])
You can loop over the users and check if the work and mobile number are present:
for user in Data['users']:
has_mobile_number = False
has_work_number = False
for phonenumber in user['phoneNumbers']:
if phonenumber['type'] == 'work':
has_work_number = True
if phonenumber['type'] == 'mobile':
has_mobile_number = True
if has_work_number and has_mobile_number:
print('Firstname', user['firstName'])
Also, I recommend not using i and j when not talking about indexes. In you code, i is a dict representing a user and j is a dict representing a phone. I replaced them with user and phonenumber for more clarity in the code above.

how to fetch only content from table by avoiding unwanted codes [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 3 years ago.
Improve this question
I was trying to fetch text content from table which works well but along with result it print unwanted codes
my code is here
searchitem = searchme.objects.filter(face = after) .values_list ("tale" , flat = True)
the contents are text
the result I receive is "querySet Prabhakaran seachitem"
but I only want o get result "Prabhakaran"
model is this
class searchme ( models.Model):
face = models.TextField()
tale = models.TextField ()
From the official django documentation :
A common need is to get a specific field value of a certain model instance. To achieve that, use values_list() followed by a get() call:
So use:
searchme.objects.values_list('tale', flat=True).get(face=after)

implement dynamic nested dictionaries? [closed]

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.

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"]

Categories