DATA SORTING WITH CUSTOM FUNCTION - python

I WANTED OUTPUT SORTED BY [A,B,C,D,E] IN THE LIST
A =['12,Boring Stuff with Python Programming,D,692617,4.6,70508',
'10,Complete C# 2D,A,364934,4.6,78989',
'5,Java Developers,B,502572,4.6,123798',
'15,Learn Python Programming Masterclass,C,240790,4.5,58677',
'3,Machine Learning A-Z,E,692812,4.5,132228',]
def order(string):
v= []
for i in string:
m = i.split(",")
v.append(m[1])
return v
print(sorted(A,key=order))
WHEN I I USE 'M[0]', IT SORTED WITH [ 5,3,10,12,15 ] BUT WHEN USING 'M[1]' THE ERROR SHOW
Traceback (most recent call last):
File "ts.py", line 82, in <module>
print(sorted(A,key=order))
File "ts.py", line 80, in order
v.append(m[1])
IndexError: list index out of range

Assuming the letters [A B C D E] always fall in the third item, you could do::
>>> print(sorted(A, key=lambda x: x.split(',')[2]))
['10,Complete C# 2D,A,364934,4.6,78989',
'5,Java Developers,B,502572,4.6,123798',
'15,Learn Python Programming Masterclass,C,240790,4.5,58677',
'12,Boring Stuff with Python Programming,D,692617,4.6,70508',
'3,Machine Learning A-Z,E,692812,4.5,132228']
Notice the key function does not take the whole list, but it takes one item from the list (the string), and returns the part of that string that should be used as they key for comparison. In this case, the third item counting by commas. Without key it defaults to using the whole item (the string) as they key, functionally speaking the identity function.

Related

accessing nested dictionaries when you know the nested key?

This one is probably pretty easy, but I can't figure it out! Suppose I have a dictionary with a nested dictionary, that I know the nested dictionary key that I can store in a variable, how would I access this value?
k = 'mynested'
nestedk = 'blah'
x = {}
x['mynested'] = {}
x['mynested']['blah'] = 1
print(x[k[nestedk]])
throws error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: string indices must be integers
There is a slight mistake in your last line print(x[k[nestedk]]). This line actually means that you are treating the k variable as a list which is actually a string and the characters of the string can only be accessed by an integer index and not by a string index.
Change the last line to the below
print(x[k][nestedk])
You can get it with x[k][nestedk]. You can access the values similar to assigning values inside dictionary. As you are assigning
X[k] = {}
and x[k][nestedk] = 1
The value is 1 and key for nested object is k so initially we get the inner dictionary by x[k] and then we get the value using nested key in your case nestedk.
Thus you have to correct your print statement like below
print(x[k][nestedk])

Sorting list of strings by a character

I got the following assignment:
For a given list of strings write a function that returns a sorted list with all strings starting with the character x at the beginning (define two lists)
I stuck here:
set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica"]
set_words_list.sort(key=str("x"))
print(set_words_list)
And then error pops out:
Traceback (most recent call last):
File "/5SortList/main.py", line 7, in <module>
set_words_list.sort(key=str("x"))
TypeError: 'str' object is not callable
It is my first time coding in Python, and I have no clue where to go from there.
On top of that, according to the task one needs to use 2 lists, yet I don't know how it can help me.
The simplest way is to split the input into two lists. One contains the elements that start with x, the other contains the rest. That's what the instructions meant by "define two lists".
Then sort each of these lists and concatenate them.
x_words = []
nox_words = []
for word in set_words_list:
if word.startswith("x"):
x_words.append(word)
else:
nox_words.append(word)
result = sorted(x_words) + sorted(nox_words)
list.sort(reverse=True|False, key=myFunc)
reverse --> Optional. reverse=True will sort the list descending. Default is reverse=False
key--> Optional. A function to specify the sorting criteria(s)
In below code we are passing myFunc to the key part of the sort function.
Function returns not e.startswith('x') since True == 1. This will sort the words starting with 'x'.
def myFunc(e):
return not e.startswith('x')
set_words_list = ["argentinax", "football", "ss", "poxland", "axmerica", 'xx']
set_words_list.sort(key=myFunc)
print(set_words_list)
set_words_list = ["argentinax", "football", "ss", "poxland", 'xamerica' ,"axmerica"]
x_first_letter = sorted([x for x in set_words_list if x[0]=='x'])
nox_first_letter = sorted([x for x in set_words_list if not x[0]=='x'])

Convert String to Dictionary

I have a string
str = "Name John"
I want to change it to a dictionary.
{"Name":"John"}
How do I achieve this?
I Have tried using comprehension but I get an error.
str = "Arjun 23344"
Name = {str.split()}
Error
Traceback (most recent call last):
File "/home/daphney/Python/AGame.py", line 2, in <module>
Name = {x.split()}
TypeError: unhashable type: 'list'
You can split:
my_dict = {str.split(" ")[0]:str.split(" ")[1]}
Note: If you have, say, Name John Smith and want the dict to be Name:Smith, then you can just change the [1] to [-1] to get the last indexed item.
You can create a dictionary using dict function by providing list of [key,value] lists (or (key,value) tuples):
my_str = "Arjun 23344"
Name = dict([my_str.split()])
print(Name) # output: {'Arjun': '23344'}
Name = dict([str.split()])
This would only work if your string always splits into exactly two words. This works because the split call returns a list of two elements, which is then stored inside a containing list, and passed to the dict constructor. The latter can work properly with a sequence (list or other) of pairs (lists or other).
This works in this particular case, but is not robust or portable.
As there are only two strings in your variable.
string = "Name Shivank"
k,v = string.split()
d = dict()
d[k] = v
print(d) #output: {'Name':'Shivank'}
you can provide a second parameter to the split function to limit the number of separations (to 1 in this case):
dict([string.split(" ",1)])

List index out of range error list reduced while iteration

I think I'm getting an error because the range of the list is reduced during iteration of the loop. I have 95 nested lists within a large list mega4, and I'm trying to delete some strings with if and else. The list ufields consist of 18 strings.
>>> for i in range(len(mega4)):
... for j in range(len(mega4[i])):
... for f in ufields:
... if (f in mega4[i][j]) is False:
... mega4[i].remove(mega4[i][j])
... else:
... pass
...
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
IndexError: list index out of range
The fourth line is basically asking if each element within mega4[i] has each strings within ufields, how can I remove the mega4[i][j] in this case?
Edit:
I followed comments below and tried building a new list but this one does not seem to work
>>> mega5 = []
>>> for i in range(len(mega4)):
... for f in ufields:
... mega5.append([x for x in mega4[i] if f in x is True])
len(mega5) is larger than len(mega4) whereas it should be the same.
Depending on how ufields is defined, you could eliminate the innermost loop by using if mega4[i][j] in ufields.
Instead of modifying mega4 within this loop, you could build up a list of what elements you want to eliminate, and then do the actual elimination afterwards (looping over your list of candidates instead of mega4 itself).
Simpler way:
result = [[sub for sub in item if sub] for item in mega4]
Your way wasn't working because you were editing list while iterating over it.

How do I unpack a list with fewer variables?

k = [u'query_urls', u'"kick"', u'"00"', u'msg=1212', u'id=11']
>>> name, view, id, tokens = k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
I need to provide 5 variables to unpack this list. Is there a way to unpack with fewer, so that tokens gets the rest of the list. I don't want to write another line to append to a list....
Thanks.
Of course I can slice a list, assign individually, etc. But I want to know how to do what I want using the syntax above.
In Python 3 you can do this: (edit: this is called extended iterable unpacking)
name, view, id, *tokens = k
In Python 2, you will have to do this:
(name, view, id), tokens = k[:3], k[3:]

Categories

Resources