trying to separate two sets of information from csv [duplicate] - python

This question already has answers here:
How to print a list in Python "nicely"
(11 answers)
Closed 5 years ago.
I've used a draft code and adapted it to suit my code but I don't know how to split the data. The question might seem a vague so I'll try to be help by saying what I want.
My code:
import csv
with open("scores.csv") as csv_data:
reader=csv.reader(csv_data,delimiter=",")
number_sorted=sorted(reader,key=lambda x:int(x[0]),reverse=True)
print(number_sorted)
I get the output:
[['25356767', 'tom'], ['443388', 'jin'], ['6744', 'trev'], ['4666', 'ryan'],
['2445', 'jones'], ['536', 'sue'], ['34', 'bob'], ['8', 'hera'], ['1',
'bill'], ['0', 'v']]
but I want the print to look like this so it looks like a leader board:
`[['25356767', 'tom'],
['443388', 'jin'],
['6744', 'trev'],
['4666', 'ryan'],
['2445', 'jones'],
['536', 'sue'],
['34', 'bob'],
['8', 'hera'],
['1', 'bill'],
['0', 'v']]`
I hope that explains my question.

Can't do that, sorry.
What you're asking to do is, essentially, altering the way the console outputs lists. Simpler (and, probably, prettier) would be to define a function to pretty print the lists.
If you did something like:
def pretty(inlist):
for score, name in inlist:
print name.rjust(10) +"| " +score
Then it would print every line in a pretty format.

Related

Extracting Strings From a List

Hi I'm fairly new to Python and needed help with extracting strings from a list. I am using Python on Visual Studios.
I have hundreds of similar strings and I need to extract specific information so I can add it to a table in columns - the aim is to automate this task using python. I would like to extract the data between the headers 'Names', 'Ages' and 'Jobs'. The issue I am facing is that the number of entries of names, ages and jobs varies a lot within all the lists and so I would like to write unique code which could apply to all the lists.
list_x = ['Names','Ashley','Lee','Poonam','Ages', '25', '35', '42' 'Jobs', 'Doctor', 'Teacher', 'Nurse']
I am struggling to extract
['Ashley', 'Lee', 'Poonam']
I have tried the following:
for x in list_x:
if x == 'Names':
for y in list_x:
if y == 'Ages':
print(list_x[x:y])
This however comes up with the following error:
"Exception has occurred: typeError X
slice indices must be integers or None or have an index method"
Is there a way of doing this without specifying exact indices?
As the comment suggested editing the data is the easiest way to go, but if you have to...
newList = oldList[oldList.index('Names') + 1:oldList.index("Ages")]
It just finds the indices of "Names" and "Ages" in the list, and extracts the bit between.
Lots can (and will) go wrong with this method though - if there's a name which is "Names", or if they are misspelt, etc.
For completeness sake, it might be not a bad idea to use an approach similar to the below.
First, build a list of indices of each of the desired headers:
list_x = ['Names', 'Ashley', 'Lee', 'Poonam', 'Ages', '25', '35', '42', 'Jobs', 'Doctor', 'Teacher', 'Nurse']
headers = ('Names', 'Ages', 'Jobs')
header_indices = [list_x.index(header) for header in headers]
print('indices:', header_indices) # [0, 4, 8]
Then, create a list of values for each header, which we can infer from the positions where each header shows up in the list:
values = {}
for i in range(len(header_indices)):
header = headers[i]
start = header_indices[i] + 1
try:
values[header] = list_x[start:header_indices[i + 1]]
except IndexError:
values[header] = list_x[start:]
And finally, we can display it for debugging purposes:
print('values:', values)
# {'Names': ['Ashley', 'Lee', 'Poonam'], 'Ages': ['25', '35', '42'], 'Jobs': ['Doctor', 'Teacher', 'Nurse']}
assert values['Names'] == ['Ashley', 'Lee', 'Poonam']
For better time complexity O(N), we can alternatively use an approach like below so that we only have one for loop over the list to build a dict object with the values:
from collections import defaultdict
values = defaultdict(list)
header_idx = -1
for x in list_x:
if x in headers:
header_idx += 1
else:
values[headers[header_idx]].append(x)
print('values:', values)
# defaultdict(<class 'list'>, {'Names': ['Ashley', 'Lee', 'Poonam'], 'Ages': ['25', '35', '42'], 'Jobs': ['Doctor', 'Teacher', 'Nurse']})

Python list of lists as a dictionary value

I have a list of lists like the following:
servers = [['serv1','10.10.10.10','00','onehost'],['serv2','10.10.10.20','01','twohost']]
I need a dictionary such as the following
Appdict = {'App': ['serv1','10.10.10.10','00','onehost'],['serv2','10.10.10.20','01','twohost']}
I've tried the zip method by zipping 2 lists but there are difficulties parsing the data in the front end.
I've also tried the below:
for i in servers:
Appdict.update(servers[i])
What would be the best way to create the dictionary? Thanks for your time!
If I understand correctly, you want this:
Appdict = {}
Appdict['App'] = servers
This will produce:
In [2723]: Appdict
Out[2723]:
{'App': [['serv1', '10.10.10.10', '00', 'onehost'],
['serv2', '10.10.10.20', '01', 'twohost']]}

appending to a dictionary

I have a python code like this:
experiment_str = ['0', '1', '2', '3', '4', '5']
conversation_dict = dict.fromkeys(experiment_str,[])
conversation_dict['0'].append(10)
I want to add 10 to only the first key but it adds to all keys. Can you please help me to understand it?
For a dictionary you shouldn't be using the .append method, simply use '=':
conversation_dict['0'] = 10
as well as this, if you want to create a new key, use the same method.

Replace sublist with another sublist - 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 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']]

Extract out nested keys into a list [duplicate]

This question already has answers here:
Loop through all nested dictionary values?
(18 answers)
Closed 5 years ago.
I have a dictionary raw_data['list'] that have values structured like so:
k, v in sorted(raw_data['list'].items()):
print(k, v)
break
1001473688 {'resolved_id': '1001473688', 'item_id': '1001473688', 'word_count': '149', 'excerpt': '“The fraudulence paradox was that the more time and effort you put into trying to appear impressive or attractive to other people, the less impressive or attractive you felt inside — you were a fraud.', 'time_favorited': '0', 'favorite': '0', 'given_url': 'http://www.goodreads.com/quotes/564841-the-fraudulence-paradox-was-that-the-more-time-and-effort', 'is_index': '0', 'status': '0', 'sort_id': 3795, 'authors': {'3445796': {'author_id': '3445796', 'item_id': '1001473688', 'name': 'David Foster Wallace', 'url': 'http://www.goodreads.com/author/show/4339.David_Foster_Wallace'}}, 'time_read': '0', 'has_image': '0', 'has_video': '0', 'given_title': 'Quote by David Foster Wallace: “The fraudulence paradox was that the more t', 'resolved_title': '“The fraudulence paradox was that the more time and effort you put into trying to appear impressive or attractive to other people, the less impressive or attractive you felt inside — you were a fraud. And the more of a fraud you felt like, the harder you tried to convey an impressive or likable image of yourself so that other people wouldn’t find out what a hollow, fraudulent person you really were. Logically, you would think that the moment a supposedly intelligent nineteen-year-old became aware of this paradox, he’d stop being a fraud and just settle for being himself (whatever that was) because he’d figured out that being a fraud was a vicious infinite regress that ultimately resulted in being frightened, lonely, alienated, etc. But here was the other, higher-order paradox, which didn’t even have a form or name — I didn’t, I couldn’t.”', 'resolved_url': 'http://www.goodreads.com/quotes/564841-the-fraudulence-paradox-was-that-the-more-time-and-effort', 'time_added': '1438693251', 'time_updated': '1439849583', 'is_article': '1'}
Some of the values within raw_data['list'] dictionary have a 'tags' key like so:
{'excerpt': '',
'favorite': '0',
'given_title': 'carlcheo.com/wp-content/uploads/2014/12/which-programming-language-should-i',
'given_url': 'http://carlcheo.com/wp-content/uploads/2014/12/which-programming-language-should-i-learn-first-pdf.pdf',
'has_image': '0',
'has_video': '0',
'is_article': '0',
'is_index': '0',
'item_id': '999554490',
'resolved_id': '999554490',
'resolved_title': '',
'resolved_url': 'http://carlcheo.com/wp-content/uploads/2014/12/which-programming-language-should-i-learn-first-pdf.pdf',
'sort_id': 3026,
'status': '0',
'tags': {'programming': {'item_id': '999554490', 'tag': 'programming'}},
'time_added': '1454096378',
'time_favorited': '0',
'time_read': '0',
'time_updated': '1454096385',
'word_count': '0'}
I need to extract out all the keys of 'tags' keys (aka the keys of the 'tags' values) into a list. I don't have much experience with nested dictionaries and struggling to figure out how I should write a nested for loop (if that is the most elegant way to the solution). Please let me know your thoughts. Thanks!
The following nested comprehension should work:
tags = [tag for v in raw_data['list'].values() for tag in v.get('tags', {})]

Categories

Resources