Extract single True/False value from JSON Twitter response ( Tweepy and Python ) - python

I am trying to write a little bit of code in an app that checks if a user is following you or not. I just want the code to return a True/False value that I can put in an if loop.
The code is:
user_id = '1234567890'
print api.show_friendship(target_id=user_id)
And it returns all this JSON, which I know nothing about but want the 'false' value from the second array for the other user under 'following' (or, alternatively, the true/false from the first array under 'followed_by'... either way is fine!):
{"relationship":{"source":{"id":0000000000,"id_str":"0000000000","screen_name":"auth_user","following":false,"followed_by":false,"following_received":false,"following_requested":false,"notifications_enabled":false,"can_dm":false,"blocking":false,"blocked_by":false,"muting":false,"want_retweets":false,"all_replies":false,"marked_spam":false},"target":{"id":123456789,"id_str":"123456789","screen_name":"other_user","following":false,"followed_by":false,"following_received":false,"following_requested":false}}}
How can I make my code return the true/false for the "following":false part?
(or, the "followed_by":false part in the first array - each array is from the user's "viewpoint" of the relationship)

Nice, solved it immediately after posting.
Try:
print json.loads(api.show_friendship(target_id=user_id))["relationship"]["target"]["followed_by"]
You can work through the JSON array by specifying each branch as you go through it (I'm sure many people know that lol, but I've never used JSON!)...

print api.show_friendship(target_screen_name=screen_name)[1].following
True

Related

searching "key" in a dictionary

Below you will see a snippet of a code where I created a dictionary in which words from a product review are stored. Now, I am writing a function that will return the number of occurrences of the word present in the dictionary. If it isn't present, it returns 0.
(This function will be used later for another purpose. As one of the member pointed, I could use dict.get() to extract the key. however, when I tried that, I got an attribute error:'SArray' object has no attribute 'get')
Can anyone point out any obvious mistake I might have made?
Thanks in advance.
Edit:
Here is the code:
word_list=turicreate.text_analytics.count_words(products['review'])
def selected_w_count(key):
if key in word_list:
return word_list[key]
else:
return 0
selected_w_count('wise')
output ->> 0
Snapshot of the code
You have a typo in selected_w_count(key) function, if key in world_list: should be if key in word_list:.
Based on your comment that the type of word_list is an array, you may want to use word_list[0].get('wise', 0) in place of the function call. This will get the dict from the array and get key 'wise' with a default value of 0.
It seems that your code returns a turicreate.SArray object but not a standard dict object, so the get function don't work.
I search for the document and find it at:
https://apple.github.io/turicreate/docs/api/generated/turicreate.SArray.html
And maybe you can use the function turicreate.SArray.dict_trim_by_keys() to filter by the given keys and use turicreate.SArray.dict_values() to get the value, just like this:
def selected_w_count(key_word):
word_list.dict_trim_by_keys([key_word], exclude=False).dict_values() if word_list.dict_trim_by_keys([key_word], exclude=False) else 0
You can also just provide a list of key words, just change it like this:
def selected_w_count(keywords_list):
word_list.dict_trim_by_keys(keywords_list, exclude=False).dict_values() if word_list.dict_trim_by_keys(keywords_list, exclude=False) else 0
The documents of these functions are here:
https://apple.github.io/turicreate/docs/api/generated/turicreate.SArray.dict_trim_by_keys.html
https://apple.github.io/turicreate/docs/api/generated/turicreate.SArray.dict_values.html
Take care that the true result will also return A SArray of list type but not just a num.
Not sure whether it works, hope it can help you.

How to get result from a dictionary with lists as the values

I have a JSON file with n number of dictionaries as listed below in the snippet. I am trying to fetch the value against the key but it fails in my code when the value is defined as a list like in the below example for key affected_packages. I tried to check why my code fails, so it looks like it pulls no data out of it this fails. I just see two brackets [] as output instead of "thunderbird-0:78.9.1-1.el8_1","thunderbird-0:78.9.1-1.el8_2","thunderbird-0:78.9.1-1.el8_3","thunderbird-0:78.9.1-1.el7_9"
{"bugzilla_description":"CVE-2021-23992 Mozilla: A crafted OpenPGP key with an invalid user ID could be used to confuse the user","cvss_score":null,"cvss_scoring_vector":null,"CWE":"CWE-347","affected_packages":["thunderbird-0:78.9.1-1.el8_1","thunderbird-0:78.9.1-1.el8_2","thunderbird-0:78.9.1-1.el8_3","thunderbird-0:78.9.1-1.el7_9"],"resource_url":"https://access.redhat.com/hydra/rest/securitydata/cve/CVE-2021-23992.json","cvss3_scoring_vector":"CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:N/A:L","cvss3_score":"4.3"}
I am doing like below in my code as I need to prepare a worksheet. Sample snippet:
for i in range(offs):
ws.cell(row=r+1+i,column=2).value = v['current'][i]
if 'affected_packages' in list(tmp1.keys()):
ws.cell(row=r+1+index1,column=11).value = tmp1['affected_packages']
print("affected_packages done")
if 'advisories' in list(tmp1.keys()):
ws.cell(row=r+1+index2,column=13).value = tmp1['advisories']
print("advisories done")
Is there a way I can pull the value correctly for those defined as a list in the dictionary? I need a way so that it won't hamper my existing logic to pull value for normal key: value since while looking up into my JSON file.
So need something which can fulfil both whether my value in the dictionary is as a list or not as a list and I can get value against the keys in my json file.
As mentioned in the other answers, you can test the type of a variable using
if type(some_variable) == list:
# do what you need to do
You do mention that your code breaks, and I guess it's because inserting into a cell expects a String, not the list you pass in the line
ws.cell(row=r+1+index1,column=11).value = tmp1['affected_packages']
So how do we get a string out of a list of strings? It's pretty easy using the join method.
my_list = ["thunderbird-0:78.9.1-1.el8_1","thunderbird-0:78.9.1-1.el8_2","thunderbird-0:78.9.1-1.el8_3","thunderbird-0:78.9.1-1.el7_9"]
as_one_string = ", ".join(my_list)
print(as_one_string)
# Prints out 'thunderbird-0:78.9.1-1.el8_1, thunderbird-0:78.9.1-1.el8_2, thunderbird-0:78.9.1-1.el8_3, thunderbird-0:78.9.1-1.el7_9'
So combining the two ideas:
if 'affected_packages' in list(tmp1.keys()):
ws.cell(row=r+1+index1,column=11).value = tmp1['affected_packages'] if type(tmp1['affected_packages']) != list else ", ".join(tmp1['affected_packages'])
print("affected_packages done")
Quick feedback because I can't comment yet: Please always include an error message and/or the output you get when running your code when you ask a question
If I understand it correctly, you just need to determine if a value in dict is list. You can do that as below:
for i in d.items(): # gets key, value as a tuple.
if isinstance(i[1],list):
print('its a list, process it accordingly')
else:
print('Not a list')
Regarding your second problem, when you don't know if it is a list or something else, you can just check the type, maybe like this:
if type(tmp1['affected_packages']) == list:
# process the list
else:
# process other types
Since you don't know the data type, having this explicit type check seems necessary.

How can I split integers from string line?

How can I split confirmed value, death value and recovered value. I want to add them to different lists. I tried to isdigit method to find value in line. Also I tried split('":'). I thought I can define value after '":'. But these are not working.
https://api.covid19api.com/total/dayone/country/us
I added all line to textlist from this page.
I just edited question for other users. My problem solved thank you.
The list actually contains a string. You need to parse it and then iterate over it to access the required values from it.
import json
main_list = ['.....']
data_points = json.parse(main_list[0])
confirmed = []
for single_data_point in data_points:
confirmed.append(single_data_point.Confirmed)
print(confirmed)
A similar approach can be taken for any other values needed.
Edit:
On a better look at your source, it looks like the initial data is not in the right JSON format to begin with. Some issues I noticed:
Each object which has a Country value does not have its closing }. This is a bigger issue and needs to be resolved first.
The country object starting from the 2nd object has a ' before the object starting. This should not be the case as well.
I suggest you to look at how you are initially parsing/creating the list.
Since you gave the valid source of your data it becomes pretty simple:
import urllib.request
import json
data = json.load(urllib.request.urlopen("https://api.covid19api.com/total/dayone/country/turkey"))
confirmed=[]
deaths=[]
recovered=[]
for dataline in data:
confirmed.append(dataline["Confirmed"])
deaths.append(dataline["Deaths"])
recovered.append(dataline["Recovered"])
print ("Confirmed:",confirmed)
print ("Deaths:", deaths)
print ("Recovered:",recovered)

Generate always unique ID every-time it called with Python

What is the best way to create a python script which by calling which, it will ALWAYS generate a new UNIQUE ID (Autoincremental)
You run the script and it will tell you 1, then close script and open again and will tell you 2.
Purpose of it is to create a script which will be used across and this ID will be used to track the latest changes and so on.
P.S. I'm not talking to make a function which will do it.
import uuid
uniqueid = uuid.uuid1()
Since you didnt provide any code, I will also not provide any code.
Solution 1: Unique ID
1) TIME: create function to give you timestamp
2) ID: create function that generate long string with random numbers and letters
This is of course 'risky' because there is a chance you will generate already existing ID, but from statistical point of view, it is so called 'impossible even if it is possible'
save in file or somewhere
Solution 2: offset - incremental
1) have file with a 0 in it.
2) open a file, read line, convert to integer, increment to +1, write in a file.
Note:
Your title is wrong. One moment you talk about UNIQUE ID, Next moment you are talking about offset. Unique ID and counting running python script are quite contradicting ideas
I assume you have a script, it will generate some result every time it is executed. Then you need need a value that (1) distinguish one result from another and (2) shows which result came last. Is that right? If so, we have many options here. In the simplest case (a script always running in the same machine) I would suggest two options
Save a count to a file
In this case, you would have a file and would read the number from it:
try:
with open('count.txt') as count_file:
content = count_file.read()
count = int(content)
except Exception:
count = 0
After doing whatever your script does, you would write to the file the value you've read, but incremented:
with open('count.txt', 'w') as count_file:
count_file.write(str(count + 1))
Save the timestamp
A simpler option, however, is not to increment a value but get a timestamp. You could use time.time(), that returns the number of seconds since Unix epoch:
>>> import time
>>> time.time()
1547479233.9383247
You will always know which result came later than the others. Personally, however, I would rather format the current time, it is easier to read and reason about:
>>> from datetime import datetime
>>> datetime.now().strftime('%Y%m%d%H%M%S')
'20190114132407'
Those are basic ideas, you may need to pay attention to corner cases and possible failures (especially with the file-based solution). That said, I guess those are quite viable first steps.
A technical note
What you want here is to a program to remember a piece of information between two or more executions, and we have a technical term for that: the information should be persistent. Since you asked for an autoincrementing feature, you wanted a persistent count. I suspect, however, you do not need that if you use the timestamp option. It is up to you to decide what to do here.
I had the same situation. I ended up in creating a CSV file so that I can map variable names.
def itemId_generator(itemIdLocation):
# Importing value of ItemID from the csv file
df = pd.read_csv(itemIdLocation)
#return value which is current ItemID in the csv file
ItemId = df.loc[0, 'ItemId']
# If loop to set limit to maximum Item ID
if ItemId>= 10000:
df.loc[0, 'ItemId'] = 1
elif ItemId<10000:
# updating the column value/data
df.loc[0, 'ItemId'] = df.loc[0,'ItemId'] + 1
else:
print("Invalid value returned")
sys.exit()
# writing new ItemID into the file
df.to_csv(itemIdLocation, index=False)
# The function .item() converts numpy integer to a normal int
return str(ItemId.item())
If there is any chance of the file being accessed concurrently, it is best to lock the file. Keep trying if the file is locked.
http://tilde.town/~cristo/file-locking-in-python.html
Old answer:
You could store it as an environment variable on the system. If not set, initialise to 1. Else increment it by 1.

Python MySQL if variable does not exists still submit

I'm doing some queries ( inserts ) to a database based on some input.
However not all the times I get all the data from the user. I still would like though to insert the data that I received. I have a table with close to
10 columns but in the data I also have some arrays.
When I'm trying to insert something I get an exception that the say input['name'] does not exists and the query is not executed.
Is there some way to quickly manage that? If a variable does isn't defined simply throw a warning like in PHP and not break the whole loop.
New to python and only thing I can think of is to check for every single variable but I'd really hope there's something more simpler than this and quicker.
Do input.get('name')
From the docs https://docs.python.org/2/library/stdtypes.html#dict.get
Return the value for key if key is in the dictionary, else default.
If default is not given, it defaults to None, so that this method never raises a KeyError.
You should look into exception handling. It sounds like you need to use an try-except-else where you're making use of input['name']

Categories

Resources