How to remove part of a data string? [closed] - python

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 5 years ago.
Improve this question
My data is in the following format:
[{u'value': 7681, u'time': u'2017-07-12T12:15:54.107488923Z'}, {u'value':
7672, u'time': u'2017-07-12T12:26:01.295268409Z'}]
I need to remove all the u prefixes from this data. How can I do that using Python 2.7? In fact, I want it to be like:
[{'value': 7681, 'time': '2017-07-12T12:15:54.107488923Z'}, {'value':
7672, 'time': '2017-07-12T12:26:01.295268409Z'}]

It's unclear what ResultSet is and its format from your question, however the following example code might be helpful:
import csv
csv_filename = 'result_set.csv'
ResultSet = {"(u'maxbotix_depth', None)": [{u'time': u'2017-07-12T12:15:54.107488923Z',
u'value': 7681},
{u'time': u'2017-07-12T12:26:01.295268409Z',
u'value': 7672}]}
with open(csv_filename, mode='wb') as csv_file:
writer = csv.writer(csv_file)
for obj in ResultSet["(u'maxbotix_depth', None)"]:
time, value = obj[u'time'], obj[u'value']
print('time: {}, value: {}'.format(time, value)) # optional
writer.writerow((time, value))
Printed output:
time: 2017-07-12T12:15:54.107488923Z, value: 7681
time: 2017-07-12T12:26:01.295268409Z, value: 7672
Contents of file created:
2017-07-12T12:15:54.107488923Z,7681
2017-07-12T12:26:01.295268409Z,7672

Related

use list values as keys to dict with keys [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 3 months ago.
Improve this question
I have a dictionary
foo = {"/" : {"bar":"returnme"} }
and a list
example = ["/","bar"]
how do I use the list to return the value in "bar" ? (i.e. identical output to
foo["/"]["bar"] )
For clarity the value of the example list changes, the example could also be:
foo = {"/" : {"bar": {"morefoo": {"returnme"}} }}
example = ["/","bar","morefoo"]
foo[example] --> "returnme"
For other functionality in the script I will need to be able to use the example list to add/remove things to the 'final' dictionary.
You have to iteratively retrieve elements from a dictionary.
def get(tree, keys):
current = tree
for key in keys:
current = current[key]
return current
and it works:
>>> get({"/": {"bar": "returnme"}}, ["/", "bar"])
'returnme'
>>> get({"/": {"bar": {"morefoo": "returnme"}}}, ["/", "bar", "morefoo"])
'returnme'
>>>

How can I organize my code according to output that I want? [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 12 months ago.
Improve this question
I have the code below.
import json
name = " "
username = " "
ip_address = " "
with open('data6.json', 'r') as myfile:
data = json.load(myfile)
for i in data:
print(i[0].get('Manufacturer'))
print(i[0].get('Name'))
print(i[0].get('IPAddress'))
The output is the code like that:
VMware, Inc.
DC01
None
None
None
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
None
DC01
None
But i want an output like:
VMware, Inc.
DC01
['192.168.1.240,fe80::350e:d28d:14a5:5cbb']
How can i organize my code according to output that i want?
data6.json is like in the below:
[[{"Manufacturer": "VMware, Inc.", "Model": "VMware7,1", "Name": "DC01"}], [{"Index": "1", "IPAddress": ["192.168.1.240,fe80::350e:d28d:14a5:5cbb"]}], [{"Name": "DC01", "UserName": null}]]
If you load your initial json File you have:
one list -> contains 3 one-element lists -> contains the dict
If you have more of these nestes Lists in files, I would recommend to flatten them
If you want your data you have to access the correct one-element list, first index, then get the element in the one-element list, then choose the right value from the dict. Additionally you should close your file handler to close all resources before further working.
with open('data6.json', 'r') as myfile:
data = json.load(myfile)
print(data[0][0]['Manufacturer'])
print(data[0][0]['Name'])
print(data[1][0]['IPAddress'])

If dictionary value exists multiple times in list of dicts, delete specific dict from list [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 3 years ago.
Improve this question
I have a function that returns a list of dictionaries like this:
[{'Status': 'Deleted', 'Name': "My First Test"}, {'Status': 'Modified', 'Name': "My First Test"}]
As you can see, "My First Test" is in there twice. Normally this wouldn't be an issue, however, based on what I know about what's happening on the back-end, the only dict that I actually want is the "Modified" dict.
Essentially, I'm looking for a way to say "if dict['Status'] == 'Modified' and dict['Status'] == 'Deleted' for the same Name, delete the one with the 'Deleted' status."
I don't know if I understood well your question.
But it's a tip:
list = [
{
'Status': 'Deleted',
'Name': "My First Test"
},
{
'Status': 'Modified',
'Name': "My First Test"
}]
filterd_list = [l for l in list if l['Status'] == 'Modified']
print(filterd_list) # Only the modified one will be printed

How can I turn integers into strings in a dict using 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 4 years ago.
Improve this question
I'm creating a dictionary from the college scorecard API, but I'm having trouble joining integer queries to my dictionary (ie. "2015.student.size"). How would I do that in my code? I've tried "str() for f in", but that doesn't seem to work.
This is what I've written in Python so far:
import requests
import json
def main():
url = 'https://api.data.gov/ed/collegescorecard/v1/schools.json'
payload = {
'api_key': "api_key_here",
'_fields': ','.join([
'school.name',
'school.school_url',
'school.city',
'school.state',
'school.zip',
]),
'school.operating': '1',
'2015.academics.program_available.assoc_or_bachelors': 'true',
'2015.student.size__range': '1..',
'school.degrees_awarded.predominant__range': '1..3',
'school.degrees_awarded.highest__range': '2..4',
'id': '240444',
}
data = requests.get(url, params=payload).json()
for result in data['results']:
print(','.join(result.values()))
main()
What happens when I run the program:
vagrant#vagrant:/vagrant/scripts$ python test.py
Madison,www.wisc.edu,University of Wisconsin-Madison,WI,53706-1380
When I add "print data":
{u'results': [{u'school.city': u'Madison', u'school.school_url': u'ww
w.wisc.edu', u'school.name': u'University of Wisconsin-Madison', u'sc
hool.state': u'WI', u'school.zip': u'53706-1380'}], u'metadata': {u'p
er_page': 20, u'total': 1, u'page': 0}}
I think you are making this more difficult than necessary. Instead of the for loop, you can do
print(data)
Or if you want each dictionary from the list to be on its own line, instead of
print(','.join(result.values()))
Just do
print(result)

Extracting All Combinations in nested dictionary 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 5 years ago.
Improve this question
I have a dictionary like:
{'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536': '0.0', '6448': '0.0'}}
And I would like to product a structure similar to preferably in Pyspark:
('6400',['6400','6401','1.0'])
('6400',['6400','6407','0.3333333333333333'])
('6400',['6400','6536','0.0'])
('6400',['6400','6448','0.0'])
If you do this in python you can use following code to produce the structure you want.
d = {'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536':
'0.0', '6448': '0.0'}}
result = []
for outer_e in d:
for inner_e in d[outer_e]:
e = [outer_e, inner_e, d[outer_e][inner_e]]
e = (outer_e, e)
result.append(e)
Little bit bulky, but another way to solve problem:
In [1]: d = {'6400': {'6401': '1.0', '6407': '0.3333333333333333', '6536': '0.0'
...: , '6448': '0.0'}}
In [2]: map(lambda item: [(item[0], [item[0], *i]) for i in item[1].items()], d.items())
Out[2]: <map at 0x104563e48>
In [3]: list(_)
Out[3]:
[[('6400', ['6400', '6401', '1.0']),
('6400', ['6400', '6407', '0.3333333333333333']),
('6400', ['6400', '6536', '0.0']),
('6400', ['6400', '6448', '0.0'])]]
And since it unordered dict object, you can't rely on order.

Categories

Resources