I have a dictionary that have year-month combination as the key and value of it. I used OrderedDict to sort the dictionary and getting result like below. In my expected result, after "2021-1", it should be "2021-2". But "2021-10" is coming in between.
{
"2020-11": 25,
"2020-12": 861,
"2021-1": 935,
"2021-10": 1,
"2021-2": 4878,
"2021-3": 6058,
"2021-4": 3380,
"2021-5": 4017,
"2021-6": 1163,
"2021-7": 620,
"2021-8": 300,
"2021-9": 7
}
My expected result should be like below. I want the dictionary to be sorted by least date to the last date
{
"2020-11": 25,
"2020-12": 861,
"2021-1": 935,
"2021-2": 4878,
"2021-3": 6058,
"2021-4": 3380,
"2021-5": 4017,
"2021-6": 1163,
"2021-7": 620,
"2021-8": 300,
"2021-9": 7,
"2021-10": 1
}
Appreciate if you can help.
If you want to customize the way sorting is done, use sorted with parameter key:
from typing import OrderedDict
from decimal import Decimal
data = {
"2020-11": 25,
"2020-12": 861,
"2021-1": 935,
"2021-10": 1,
"2021-2": 4878,
"2021-3": 6058,
"2021-4": 3380,
"2021-5": 4017,
"2021-6": 1163,
"2021-7": 620,
"2021-8": 300,
"2021-9": 7
}
def year_plus_month(item):
key = item[0].replace("-", ".")
return Decimal(key)
data_ordered = OrderedDict(sorted(data.items(), key=year_plus_month))
print(data_ordered)
I used Decimal instead of float to avoid any wonky floating point precision.
Related
I want to print the 5th index value of an enumerated list. In the example code below, the 5th index value is 555. I want to print only the 555 value. The code below prints all index values from 0-8. I just want to print the value at index 5, which is 555. What is the best way to do this?
num_list = [000, 111, 222, 333, 444, 555, 666, 777, 888]
for i, d in enumerate (num_list):
print(i, d)
I solved the issue. The goal was to print the value of the nth index (i.e. 5th index) of an enumerated object. Additional the value should only be printed once. I believe the problem with the code was the indented print statement. Below is the solution.
num_list = [000, 111, 222, 333, 444, 555, 666, 777, 888]
for i, d in enumerate (num_list):
x = num_list[5]
print(x)
I am creating custom functions in which a user can specify an argument value in the custom function. The argument will be a key in a dictionary that is local to the custom function.The value associated with the key will an argument to an internal function that is nested within the custom function.
I have attached a simple example where the custom function is called Average. If I can get help on this simple example, I can use the logic to solve the more complex examples that I am working with.
# Python program to get average of a list
def Average(lst,rnd = 'three'):
rndtype = {'three':3,'four':4}
return round(sum(lst) / len(lst),rndtype[rnd].values())
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst,'three')
The error I get is the following:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-10-a7c034956fd8> in <module>
----> 1 average = Average(lst,'three')
<ipython-input-6-b1d1ab69b2a6> in Average(lst, rnd)
2 def Average(lst,rnd = 'three'):
3 rndtype = {'three':3,'four':4}
----> 4 return round(sum(lst) / len(lst),rndtype[rnd].values())
AttributeError: 'int' object has no attribute 'values'
The values() function applies to a dictionary, you are applying it to an element of the dictionary. You just have to remove the values() call from rndtype[rnd].
def Average(lst,rnd = 'three'):
rndtype = {'three':3,'four':4}
return round(sum(lst) / len(lst),rndtype[rnd])
lst = [15, 9, 55, 41, 35, 20, 62, 49]
average = Average(lst,'three')
A little confused on what you are trying to do but is this along the lines of what you are looking for? This should be right. In your parameters you should pass in just the lst and the rnd value.
# Python program to get average of a list
def Average(lst,rnd):
rndtype = {'three':3,'four':4}
return round(sum(lst)/len(lst), rndtype[rnd])
lst = [15, 10, 55, 41, 35, 20, 62, 49]
average = Average(lst,'three')
I've got a list of dictionaries of dictionaries... Basically, it is just big piece of JSON. Here how looks like one dict from a list:
{'id': 391257, 'from_id': -1, 'owner_id': -1, 'date': 1554998414, 'marked_as_ads': 0, 'post_type': 'post', 'text': 'Весна — время обновлений. Очищаем балконы от старых лыж и API от устаревших версий: уже скоро запросы к API c версией ниже 5.0 перестанут поддерживаться.\n\nОжидаемая дата изменений: 15 мая 2019 года. \n\nПодробности в Roadmap: https://vk.com/dev/version_update_2.0', 'post_source': {'type': 'vk'}, 'comments': {'count': 91, 'can_post': 1, 'groups_can_post': True}, 'likes': {'count': 182, 'user_likes': 0, 'can_like': 1, 'can_publish': 1}, 'reposts': {'count': 10, 'user_reposted': 0}, 'views': {'count': 63997}, 'is_favorite': False}
And I want to dump each dict to frame. if I just do
data = pandas.DataFrame(list_of_dicts)
I get a frame where are only two columns: first one contains keys, and another one contains data, like this:
I tried doing it in a loop:
for i in list_of_dicts:
tmp = pandas.DataFrame().from_dict(i)
data = pandas.concat([data, tmp])
print(i)
But I face ValueError:
Traceback (most recent call last):
File "/home/keddad/PycharmProjects/vk_group_parse/Data Grabber.py", line 68, in <module>
main()
File "/home/keddad/PycharmProjects/vk_group_parse/Data Grabber.py", line 61, in main
tmp = pandas.DataFrame().from_dict(i)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/frame.py", line 1138, in from_dict
return cls(data, index=index, columns=columns, dtype=dtype)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/frame.py", line 392, in __init__
mgr = init_dict(data, index, columns, dtype=dtype)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 212, in init_dict
return arrays_to_mgr(arrays, data_names, index, columns, dtype=dtype)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 51, in arrays_to_mgr
index = extract_index(arrays)
File "/home/keddad/anaconda3/envs/vk_group_parse/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 320, in extract_index
raise ValueError('Mixing dicts with non-Series may lead to '
ValueError: Mixing dicts with non-Series may lead to ambiguous ordering.
How, after this, I can get dataframe with one post (one dictionary in the list is one post) and all the data in it as columns?
I can't figure out the df exactly but I think you simply need to do a reset_index and all the data which is currently(it seems):
df.reset_index(inplace=True)
Another thing if you want the keys as columns:
df = pd.Dataframe.from_dict(orient='columns')
# or try `index` in columns if you don't get desired results
In a for loop:
l = []
for i in dict.keys:
l.append(pd.DataFrame.from_dict(dict[i], orient='columns'))
df = pd.concat(l)
Not quite sure what you are trying to do, but do you mean something like this?
You can see inside the data by just printing the dataframe. Or you can print each one by the following code.
data = pandas.DataFrame(list_of_dicts)
print(data)
for i in data.loc[:, data.columns]:
print(data[i])
I am currently experiencing an issue whenever I try to evaluate an individual using the GP portion of DEAP.
I receive the following error:
Traceback (most recent call last):
File "ImageGP.py", line 297, in <module>
pop, logs = algorithms.eaSimple(pop, toolbox, 0.9, 0.1, 60, stats=mstats, halloffame=hof, verbose=True)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/deap/algorithms.py", line 148, in eaSimple
for ind, fit in zip(invalid_ind, fitnesses):
File "ImageGP.py", line 229, in evalFunc
func = toolbox.compile(expr=individual)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/deap/gp.py", line 451, in compile
return eval(code, pset.context, {})
File "<string>", line 1
lambda oValue,oAvg13,oAvg17,oAvg21,sobelVal(v),sobelVal(h),edgeVal,blotchVal: [[[0, 75, 82.2857142857, 83.0, 82.9090909091, 4, 12, 4, 180], ... Proceed to print out all of my data ... [0, 147, 151.244897959, 150.728395062, 150.73553719, 248, 244, 5, 210]]]
^
SyntaxError: invalid syntax
If anyone has any ideas about what could be causing this problem, then I would really appreciate some advice. My current evaluation function looks like this:
def evalFunc(individual, data, points):
func = toolbox.compile(expr=individual)
total = 1.0
for point in points:
tmp = [float(x) for x in data[point[1]][point[0]][1:9]]
total += int((0 if (func(*tmp)) < 0 else 1) == points[2])
print ("Fitness: " + str(total))
return total,
Where the data contains the data being used (the values for the 8 variables listed in the error) and point specifying the x and y co-ordinates from which to get those 8 values. Thank you for your suggestions!
So I have this file with these values:
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
Stored into a dictionary like this:
{'ARG': (40, 18, 24, 28), 'ALG': (15, 5, 2, 8), 'AFG': (13, 0, 0, 2)}
I have a function that has the user punch in the key, and it should return the tuple with the numbers in it.
However, if I were to type in, say, AFG, I get:
Traceback (most recent call last):
File "C:\Users\username\Dropbox\Programming\Python\Project3.py", line 131, in <module>
main()
File "C:\Users\username\Dropbox\Programming\Python\Project3.py", line 110, in main
findMedals(countryDictionary, MedalDictionary)
File "C:\Users\username\Dropbox\Programming\Python\Project3.py", line 88, in findMedals
answer.append([medalDict[medalCount]])
KeyError: (13, 0, 0, 2)
As you can see, the KeyError gives out the correct value for the inputted key, but why is it still complaining about it? Doesn't KeyError mean the key didn't exist?
My code:
def findMedals(countryDict, medalDict):
search_str = input('What is the country you want information on? ')
for code, medalCount in medalDict.items():
if search_str in code:
answer.append([medalDict[medalCount]])
else:
answer = ['No Match Found']
The problem is on this line:
answer.append([medalDict[medalCount]])
You are iterating over medalDict with for code, medalCount in medalDict.items():. This already assigns medalCount to the value associated with the key code. Your dict doesn't have a key represented by the tuple of medals. Therefore, it errors when you ask for medalDict[medalCount].
You can fix this by:
answer.append([medalCount])
Hope this helps