compare dictionary values with float number - python-3.x

How can I compare the dictionary values with float i.e if I had the following dictionary:
{
'F2': 0.5896643972009248,
'F3': 0.5742879655443124,
'F1': 0.5899210024965614,
'F11': 0.6086413936684749,
'F4': 0.5924462845088885,
'F6': 0.5659846155839213,
'F10': 0.6339183933852852,
'F9': 0.5597757560369959,
'F5': 0.5633086160491567,
'F7': 0.556301751221009,
'F12': 0.8346634117283984,
'F8': 0.5163509611989721
}
and I want to compare each value in this dictionary with float and if the dictionary values are greater than the given float number the output will be each key corresponding value if not block (didn't output) the key and value.

I don't what did you mean with "block the value and key", so I'm just returning the dictionary with values greater than a given float.
You can try this solution with dict comprehension:
def compare_dict_values(dictionary, given_float):
return {i: dictionary[i] for i in dictionary if dictionary[i] > given_float}

Related

sum the values of dictionary only if the keys is equal or greater than x

Given a dictionary which contains keys and values, and I want sum the values based on the keys value. For example, {1:10, 2:20, 3:30, 4:40, 5:50, 6:60}, and sum the values only if is equal or greater than 2 in keys, which output is 200.
x =2
count = 0
for key, value in dictionary.items():
while key == x:
count += 1[value]
And my output is none, and I don't know what I am missing on.
Try this. Your way of iterating over the dictionary items is correct, but inside the loop, you need to check if the current key is greater than or equal to your required key. Only then you should increment the count with the value corresponding to that key which can be retrieved in this way - dictionary[key] or you can simply add the value like count+=value
dictionary = {1:10, 2:20, 3:30, 4:40, 5:50, 6:60}
x=2
count = 0
for key,value in dictionary.items():
if key>=x:
count += dictionary[key]
print(count)
your code is incomplete and won't run as-is, so it's difficult to speculate why you're getting an output of None.
in your requirements you mention "equal or greater than 2" but your code has "key == x". This should be "key >= x".
inside your for loop you have a while. Fixing other issues this would result in an infinite loop. You want an if, not a while.
fixing those things and making an assumption or two, your code would be:
x = 2
count = 0
for key, value in dictionary.items():
if key >= x:
count += value
Alternately, you could write it in a single line of code:
sum ( v for k, v in dictionary.items() if k >= x )
I believe you just need to do as below:
count = 0
for key, value in dictionary.items():
if key >= n:
count += value

How to convert percentage to decimal when it is in list

rstocks = ['5.57%','3.95%','5.26%','5.49%','-1,80%']
stocks =[]
for i in rstocks:
stock = rstocks[i]//100
stocks.append(stock)
It keeps showing
TypeError: list indices must be integers or slices, not str
There have two several errors in your code.
You may be mistakenly put the value -1,80% instead of -1.80%.
All the elements of your list are strings and strings have no integer
division
To get integer division of your element of the list, first, you need to convert the element into integer then use operator. Look at my code below. I convert all the elements into float then multiplied it to 100.
rstocks = ['5.57%', '3.95%', '5.26%', '5.49%', '-1.80%']
stocks = []
for x in rstocks:
stocks.append(float(x.strip('%'))*100)
print(stocks)
Output
[557.0, 395.0, 526.0, 549.0, -180.0]
Further you need to get integer value then you can typecast float to int.
int(float(x.strip('%'))*100)
Or typecast later all the elements of stocks.
print([int(s) for s in stocks])
I'm assuming that the value at last index on 'rstocks' is '-1.80%' instead of '-1,80%'. You can get a substring of the values in the loop and change the data type to float.
rstocks = ['5.57%','3.95%','5.26%','5.49%','-1.80%']
stocks =[]
for i in rstocks:
stock = float(i[:-1])
stocks.append(stock)

Python: Is there any way to sort a dictionary by integer value

Is there any way to find value number in a dictionary, say 3, without knowing the key in python?
I do know that dictionaries do not have an order.
All i can get are arbitrary elements using
dict[dict.keys()[0]]
Thanks in advance.
So, if i understand correctly, you are looking for all keys with the value 3. That can be achieved by itering through the keys and comparing:
output = []
for key, value in dict.items():
if value == 3:
output.append((key, value))
print(output)
If you wanna simply sort by integer values, try:
sorted(dict.items(), key=lambda i:i[1])

How to get list of indices for elements whose value is the maximum in that list

Suppose I have a list l=[3,4,4,2,1,4,6]
I would like to obtain a subset of this list containing the indices of elements whose value is max(l).
In this case, list of indices will be [1,2,5].
I am using this approach to solve a problem where, a list of numbers are provided, for example
l=[1,2,3,4,3,2,2,3,4,5,6,7,5,4,3,2,2,3,4,3,4,5,6,7]
I need to identify the max occurence of an element, however in case more than 1 element appears the same number of times,
I need to choose the element which is greater in magnitude,
suppose I apply a counter on l and get {1:5,2:5,3:4...}, I have to choose '2' instead of '1'.
Please suggest how to solve this
Edit-
The problem begins like this,
1) a list is provided as an input
l=[1 4 4 4 5 3]
2)I run a Counter on this to obtain the counts of each unique element
3)I need to obtain the key whose value is maximum
4)Suppose the Counter object contains multiple entries whose value is maximum,
as in Counter{1:4,2:4,3:4,5:1}
I have to choose 3 as the key whose value is 4.
5)So far, I have been able to get the Counter object, I have seperated key/value lists using k=counter.keys();v=counter.values()
6)I want to get the indices whose values are max in v
If I run v.index(max(v)), I get the first index whose value matches max value, but I want to obtain the list of indices whose value is max, so that I can obtain corresponding list of keys and obtain max key in that list.
With long lists, using NumPy or any other linear algebra would be helpful, otherwise you can simply use either
l.index(max(l))
or
max(range(len(l)),key=l)
These however return only one of the many argmax's.
So for your problem, you can choose to reverse the array, since you want the maximum that appears later as :
len(l)-l[::-1].index(max(l))-1
If I understood correctly, the following should do what you want.
from collections import Counter
def get_largest_most_freq(lst):
c = Counter(lst)
# get the largest frequency
freq = max(c.values())
# get list of all the values that occur _max times
items = [k for k, v in c.items() if v == freq]
# return largest most frequent item
return max(items)
def get_indexes_of_most_freq(lst):
_max = get_largest_most_freq(lst)
# get list of all indexes that have a value matching _max
return [i for i, v in enumerate(lst) if v == _max]
>>> lst = [3,4,4,2,1,4,6]
>>> get_largest_most_freq(lst)
4
>>> get_indexes_of_most_freq(lst)
[1, 2, 5]
>>> lst = [1,2,3,4,3,2,2,3,4,5,6,7,5,4,3,2,2,3,4,3,4,5,6,7]
>>> get_largest_most_freq(lst)
3
>>> get_indexes_of_most_freq(lst)
[2, 4, 7, 14, 17, 19]

How to retrieve the max key and max value from a dictionary?

a = ['also', 'akin', 'akee','ague', 'aero', 'anes','here','beer','bute', 'byre', 'came', 'case', 'doze', 'down', 'drek', 'drew', 'dyes', 'fret', 'freo']
i = 'e'#i is user guess input
dic = {}
for item in a:
key = ''
for chr in item:
if chr == i:
key += i
else:
key += '-'
if key not in dic:
dic[key] = []
dic[key].append(item)
print(dic)
c = max(k for k, v in dic.items())
d = max(v for k, v in dic.items())
print('\nmax key:',c)
print('\nmax value:',d)
Output:
{'---e': ['ague', 'bute', 'byre', 'came', 'case', 'doze'], '--ee': ['akee'], '----': ['also', 'akin', 'down'], '-e-e': ['here'], '-ee-': ['beer'], '--e-': ['anes', 'drek', 'drew', 'dyes', 'fret', 'freo'], '-e--': ['aero']}
max key: -ee-
max value: ['here']
In the above example, a is a list of words. When the user guess a letter, for example 'e', the program iterates through each word in the list. Replace any letter that is not 'e' to a dash '-'.
I tried to map that result into a dictionary to keep track of the each group of words that where letter 'e' occurs in the same position.
Now, i want to retrieve the group of words(or key) with the largest number of words. Judging by the output, i'm not doing that because key'-e--' has the largest number of words.
I've also tried
max(dic.keys())
max(dic)
dic.get(max(dic.keys()))
Am i not fully understand the concept of max key and values for a dictionary?
Please suggest how i can fix this.
Thanks
In your question, the notion of max means being associated with the largest list., or being the largest list
max(dic.keys(), key=lambda x: len(dic[x]))
Will give you the maximum of dic's keys
Also,
sorted(dic.items(), key=lambda x:len(x[1]), reverse=True)
(in this example, lambda (x, y): len(y) works in python 2, not sure about python 3)
Will output a list of key, value tuples sorted by number of matches:
[('---e', ['ague', 'bute', 'byre', 'came', 'case', 'doze']), ('--e-', ['anes', 'drek', 'drew', 'dyes', 'fret', 'freo']), ('----', ['also', 'akin', 'down']), ('-e-e', ['here']), ('--ee', ['akee']), ('-e--', ['aero']), ('-ee-', ['beer'])]
Edit, no lambda
Without using a lambda, you'd be using a regular function:
def myMax(value_tuple):
key, value = value_tuple
return len(value)
and using it like so:
max(dic.items(), key=myMax)
Retrieve max key:
max(MyDictionary.keys(), key=type).
Retrieve max value:
max(MyDictionary.values(), key=type)
Replace type with the key type in both cases. i.e int
Hope it helps.

Resources