How to use sort function in vim script to sort a dictionary?. The help documentation doesn't seems to provide clear information on how a particular element in the dictionary can be sorted.
For eg: I am getting the quickfix items by calling getqflist(). How to sort this quickfix dictionary items with respect to line numbers?
Define your comparison function, save result of the getqflist() to a variable and call sort(v, f)
Example:
function! LineLessThan(leftArg, rightArg)
if a:leftArg['line'] == a:rightArg['line']
return 0
elseif a:leftArg['line'] < a:rightArg['line']
return -1
else
return 1
endif
endfunction
function! KeyLessThan(leftArg, rightArg)
if a:leftArg['key'] ==# a:rightArg['key']
return 0
elseif a:leftArg['key'] <# a:rightArg['key']
return -1
else
return 1
endif
endfunction
let g:a = [{'line': 3, 'key': 'd'}, {'line': 1, 'key': 'e'}, {'line': 5, 'key': 'b'}, {'line': 2, 'key': 'a'}, {'line': 4, 'key': 'c'}]
call sort(g:a, function("LineLessThan"))
echo g:a
call sort(g:a, function("KeyLessThan"))
echo g:a
Related
def match(text, pattern):
if not pattern: return not text
first_match = bool(text) and pattern[0] in {text[0], '.'}
return first_match and match(text[1:], pattern[1:])
I'm new to python and I don't understand the syntax. What is the purpose of elements in braces and what does "bool(text) and pattern[0] in {text[0], '.'}"
In python, braces are used to create either a dictionary, or a set.
my_set = {1, 2, 3}
my_dict = {'a': 1, 'b': 2, 'c': 3}
bool(text) and pattern[0] in {text[0], '.'} is checking whether the text is true (i.e. not empty or false), and the first element in pattern is either equal to text[0] or is a '.'
If we were to destruct your function into distinct pieces, it will be easier to understand
def match(text: str, pattern: str) -> bool:
# if pattern is an empty string or None
if not pattern:
# True if text is empty string or None, otherwise - false
result: bool = not text
return result
# If text is empty or None return False
if not text:
return False
# Equivalent to set(first letter of text, dot)
# We use set/{} instead of list/[] or tuple/() to remove duplicates,
# however i don't see why should we care about duplicated dots here
subset: set = {text[0], '.'}
# If first letter of pattern is not in subset, return False
if pattern[0] not in subset:
return False
# Go one level deeper in recursion and return it's answer
result: bool = match(text[1:], pattern[1:])
return result
About curly braces. In python they mean two things:
dict / dictionary: {"foo": "bar", "count": 10}
set / unique list: {1, 2, 3, 3} will create set {1, 2, 3}
Follow the links to learn more from python's docs
I'm trying to find a way to iterate through a text file and list to find character frequency. I understand that I could use Count() for this. But Count() gives everything including spaces periods and whatnots. Also it does not show the character frequency in alphabetical order. I found a way to do it and it works but not really. I'll explain later. Also when I try to put the frequency I get a KeyError. I'll also explain.
I don't want to put my whole project on here so I'll explain some stuff first. I have a separate list called alphabet_list which includes the alphabet. There's a text file that is already read through and converted into uppercase called new_text.
Character frequency Code:
for i in range(len(alphabet_list)):
for c in new_text:
if c == alphabet_list[i]:
count += 1
else:
count = 0
print(alphbet_list[i] + " " + str(count)
i += 1
Output
A 0
A 0
.
.
.
A 1
A 0
.
.
.
B 0
.
.
.
B 1
B 2
B 0
.
.
.
Z 0
P.S the str(count) is temporarily there because I want to see how it looks like print out, I needed to store the result in dictionary
My output would be that, like I said it works but not really. It will iterate but it iterates through every letter and prints out the result already and does not iterate the whole text file and just print final result. It will add to the result if there is another letter same as before right next to each other. Ex (... bb...) it will be B 1, B 2 like shown in my output. And for some reason when I use return it doesn't work. It returns nothing and just ends the program.
Second Code with KeyError:
I skipped the problem on top because I couldn't find the answer and didn't want to waste my time but ran into another problem lol*
for i in range(len(alphabet_list)):
for c in new_text:
if c == alphabet_list[i]:
count += 1
else:
count = 0
c_freq[alphabet_list[i]] == count
print(c_freq)
i += 1
This one was pretty simple I got a KeyError: 'A'.
I tried only doing the
i = 3 #just random number to test
count = 50
c_freq[alphabet_list[i]] == count
print(c_freq)
and it works, so I'm thinking that problem is also related to the problem above(? maybe). Anyways any help would be great. Thanks!
Sorry for long question but I really needed help.
This should help you:
lst = ['A', 'Z', 'H', 'A', 'B', 'N', 'H', 'Y', '.' , ',','Z'] #Initial list. Note: The list also includes characters such as commas and full stops.
alpha_dict = {}
for ch in lst:
if ch.isalpha(): #Checks if the character is an alphabet
if ch in alpha_dict.keys():
alpha_dict[ch] += 1 #If key already exists, value is incremented by 1
else:
alpha_dict[ch] = 1 #If key does not exist, a new key is created with value 1
print(alpha_dict)
Output:
{'A': 2, 'Z': 2, 'H': 2, 'B': 1, 'N': 1, 'Y': 1}
Since you want the output to be sorted in alphabetical order, add these lines to your code:
key_list = list(alpha_dict.keys()) #Creates a list of all the keys in the dict
key_list.sort() #Sorts the list in alphabetical order
final_dict = {}
for key in key_list:
final_dict[key] = alpha_dict[key]
print(final_dict)
Output:
{'A': 2, 'B': 1, 'H': 2, 'N': 1, 'Y': 1, 'Z': 2}
Thus, here is the final code:
lst = ['A', 'Z', 'H', 'A', 'B', 'N', 'H', 'Y', '.' , ',','Z']
alpha_dict = {}
for ch in lst:
if ch.isalpha():
if ch in alpha_dict.keys():
alpha_dict[ch] += 1
else:
alpha_dict[ch] = 1
key_list = list(alpha_dict.keys())
key_list.sort()
final_dict = {}
for key in key_list:
final_dict[key] = alpha_dict[key]
print(final_dict)
Output:
{'A': 2, 'B': 1, 'H': 2, 'N': 1, 'Y': 1, 'Z': 2}
How can I print a nested python dictionary in a specific format?
So, my dictionary is looks like this:
dictionary = {'Doc1':{word1: 3, word2: 1}, 'Doc2':{word1: 1, word2: 14, word3: 3}, 'Doc3':{word1: 2}}
I tried the following way:
for x, y in dictionary.items():
print(x,":", y)
But it will printL`
Doc1: {word1:3, word2: 1}
Doc2: {word1:1, word2:14, word3:3}
Doc3: {word1:2}
How to get rid of the bracket and print the plain information?
I want to print on the following format:
Doc1: word1:3; word2:1
Doc2: word1:1; word2:14; word3: 3
Doc3: word1:2;
:
in your case 'y' is a dict, so if you want to print it differently you can override the repr (representation of the object) or dict.
alternatively you can use some recursion here
def print_d(dd):
if type(dd) != dict:
return str(dd)
else:
res = []
for x,y in dd.items():
res.append(''.join((str(x),':',print_d(y))))
return '; '.join(res)
if __name__=='__main__':
dictionary = {'Doc1':{'word1': 3, 'word2': 1}, 'Doc2':{'word1': 1, 'word2': 14, 'word3': 3}, 'Doc3':{'word1': 2}}
for x, y in dictionary.items():
print(x,": ", print_d(y))
Aside from the fact that your original dictionary declaration is not valid python unless each word is a defined variable, this seems to work:
import json
print(json.dumps(dictionary).replace("{","").replace(',','').replace("}","\n").replace('"',''))
Result:
Doc1: word1: 3 word2: 1
Doc2: word1: 1 word2: 14 word3: 3
Doc3: word1: 2
I've run into this familiar error (TypeError: 'int' object is not iterable) in my code, but can't figure out how to fix it. I'm trying to add up the value of everything in the market, so I set up a loop that multiplies 1 banana by $4, then subtracts a banana from the stock, moves onto the next item, and skips items that have zero stock left. I want it to continue until all items stock are zero, essentially adding up the value of all items in the market. The compute_total_value function is the one that SHOULD do this, but the error pops up. Here is the error:
Traceback (most recent call last):
File "/Users/sasha/PycharmProjects/untitled2/shopping.py", line 62, in <module>
total_market_value = compute_total_value(market_items)
File "/Users/sasha/PycharmProjects/untitled2/shopping.py", line 49, in compute_total_value
while sum(stock[items]) != 0:
TypeError: 'int' object is not iterable
Here is my code:
# Here is the market
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_total_value(food):
total = 0
for items in food:
while sum(stock[items]) != 0: #error is on this line
if stock[items] != 0:
total += prices[items]
stock[items] -= 1
else:
continue
if sum(stock[items]) == 0:
break
return total
market_items = ["banana", "orange", "apple", "pear"]
total_market_value = compute_total_value(market_items)
print (total_market_value)
Well, the problem is very simple. The function sum() requires an iterable element to work; but you have stock[items]... stock is a dictionary and items is a string key; for example stock['banana'] whose value is 6 that is an integer and not is a iterable.
One possible solution is: sum(stock.values()), since stock.values() returns a list of all values in the dictionary.
But, for your goal it is not necessary to use the function sum.
In your code, the solution can be:
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def compute_total_value(food):
total = 0
for items in food:
while stock[items] != 0:
total += prices[items]
stock[items] -= 1
return total
market_items = ["banana", "orange", "apple", "pear"]
total_market_value = compute_total_value(market_items)
print (total_market_value)
str = 'strings'
new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }
How can I get each letter in the string assigned to the value in the dictionary by match 'letter-key' and then summarize the values?
Thanks
s = 'strings' #Don't name a variable str, that shadows the builtin str
new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }
sum_of_chars = sum([newD.get(k,0) for k in s]) #assuming 0 as default for "not in dictionary"
This takes advantage of the fact that:
Strings are iterable. for i in s: print(i) would print each character, seperately.
Dictionaries have a .get(key[,default]) 1 that can take an option argument for "return this value if the key doesn't exist.
I'm using the built-in sum on a list comprehension for the sake of brevity. Brevity can both be a virtue or a vice, but, hey, one list comp is still usually pretty readable after you know what they are.
string = 'strings'
new_D = {'r': 1, 's': 1, 't': 1, 'r' : 3, 'i' : 4 }
sum_of_chars = 0
for character in string:
if character in new_D:
sum_of_chars += new_D[character]
else:
sum_of_chars += 1 # Default?
print(sum_of_chars)
btw, you should not use the name str because it shadows the builtin str and there's a mistake in your dictionary. It contains the entry r two times which doesn't make sense.