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.
Related
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'
>>>
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.
The community reviewed whether to reopen this question 10 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have odict_items that is looking like below. Here is the printed output of Ordereddict items that I have
odict_items([('S.No', '1'), ('Name', 'Ventura'), ('Location', 'Ph'), ('OL', 'ML'), ('Tech', 'IT'), ('Value', 223)])
odict_items([('S.No', '4'), ('Name', 'Ventura'), ('Location', 'Ph'), ('OL', 'ML'), ('Tech', 'IT'), ('Value', 223)])
odict_items([('S.No', '15'), ('Name', 'Ventura'), ('Location', 'Ph'), ('OL', 'ML'), ('Tech', 'IT'), ('Value', 223)])
How can I access the S.No key from each item and group the values 1, 4, 15?
I have to assume here that you have something similar to the following situation at some point:
ods = [ OrderedDict(<your data>), OrderedDict(<your data>), OrderedDict(<your data>) ]
for d in ods:
print(d.items())
If you still have the dictionaries these came from, you can and should access the value using d['S.No'].
If for some reason you do not still have the OrderedDicts themselves, you can make a function to get the value:
def get_sno(od_items):
for item in od_items:
if item[0] == 'S.No':
return item[1]
return None
Used as such:
snos = []
for d in ods:
snos.append(get_sno(d.item()) # preferably snos.append(d['S.No']) instead
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)
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 4 years ago.
Improve this question
I have a list:
Online = [['Robot1', '23.9', 'None', '0'], ['Robot2', '25.9', 'None', '0']]
and i want to replace the sublist if i received different values:
NewSublist1 = ['Robot1', '30.9', 'Sending', '440']
NewSublist2 = ['Robot2', '50']
And i want:
Online = [['Robot1', '30.9', 'Sending', '440'], ['Robot2', '50']]
The number of the sublist elements could change. The only thing that is the same is the Robot id. So i want to make a search, see if the Robot id is on the Online list and replace the sublist with the new one.
You can create a dictionary mapping the robot IDs in your new sublists to the actual new sublists, then look up the existing robot IDs in that dict and replace accordingly.
>>> Online = [['Robot1', '23.9', 'None', '0'], ['Robot3', 'has no replacement'], ['Robot2', '25.9', 'None', '0']]
>>> NewSublists = [['Robot1', '30.9', 'Sending', '440'], ['Robot2', '50'], ['Robot4', 'new entry']]
>>> newsub_dict = {sub[0]: sub for sub in NewSublists}
>>> [newsub_dict.get(sub[0], sub) for sub in Online]
[['Robot1', '30.9', 'Sending', '440'],
['Robot3', 'has no replacement'],
['Robot2', '50']]
This will loop over each element in the list once, giving it a complexity of O(n), n being the number of elements in the Online list. If, instead, you make Online also a dictionary mapping robot IDs to sublists, you could get this down to O(k), k being the number of new sublists.
If you also want to add elements from NewSublists to Online if those are not yet present, you should definitely convert Online to a dict as well; then you can simply update the dict and get the values. Ir order matters, make sure to use a collections.OrderedDict or Python 3.7.
>>> online_dict = {sub[0]: sub for sub in Online}
>>> online_dict.update(newsub_dict)
>>> list(online_dict.values())
[['Robot1', '30.9', 'Sending', '440'],
['Robot3', 'has no replacement'],
['Robot2', '50'],
['Robot4', 'new entry']]
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