How do I get dictionary from variable coin which I have define in my code. There are 32 elements in variable coin but I'm getting only one key and value which is TUSD in last line.
import requests
import json
r=requests.get('https://koinex.in/api/ticker')
koinexData=r.json()
koinexprice = koinexData['stats']['inr']
for coin in koinexprice:
print(coin)
coindata={}
coindata["koinex"]={
coin:{
"SellingPrice":koinexprice[coin]["highest_bid"],
"buyingPrice":koinexprice[coin]["lowest_ask"]
}
}
# data.append(coindata)
# print(data)``
# s = json.dumps(coindata)
print(s)
You keep overwriting your coindata dictionary inside the loop, which is why only the last value remains. The second issue with your code is that you keep overriding the coindata['koinex'] dictionary inside the loop. This should be a list not a dictionary because you'll keep adding values to it.
If you move the initialization code outside the loop, you will not have this problem:
coindata = {}
coindata['koinex'] = [] # this should be a list, not a dictionary
for coin in koinexprice:
print(coin)
# Create a temporary dictionary d to hold the data you want
# to add to coindata
d = {coin: {'SellingPrice': koinexprice[coin]['highest_bid'],
'buyingPrice': koinexprice[coin]['lowest_ask']}
}
coindata["koinex"].append(d) # add the new dictionary to the list
print(coindata)
Related
I have created a list during a for loop which works well but I want create a dictionary instead.
from System.Collections.Generic import List
#Collector
viewPorts = list(FilteredElementCollector(doc).OfClass(Viewport))
#create a dictionary
viewPortDict = {}
#add Sheet Number, View Name and boxoutline to dictionary
for vp in viewPorts:
sheet = doc.GetElement(vp.SheetId)
view = doc.GetElement(vp.ViewId)
vbox = vp.GetBoxOutline()
viewPortDict = {view.ViewName : {'sheetNum': sheet.SheetNumber, 'viewBox' : vbox}}
print(viewPortDict)
The output from this is as follows:
{'STEEL NOTES': {'viewBox': <Autodesk.Revit.DB.Outline object at 0x000000000000065A [Autodesk.Revit.DB.Outline]>, 'sheetNum': 'A0.07'}}
Which the structure is perfect but I want it to grab everything as while it does the for loop it seems to stop on the first loop. Why is that? And how can I get it to keep the loop going?
I have tried various things like creating another list of keys called "Keys" and list of values called "viewPortList" like:
dict.fromkeys(Keys, viewPortList)
But I always have the same problem I am not able to iterate over all elements. For full disclosure I am successful when I create a list instead. Here is what that looks like.
from System.Collections.Generic import List
#Collector
viewPorts = list(FilteredElementCollector(doc).OfClass(Viewport))
#create a dictionary
viewPortList = []
#add Sheet Number, View Name and boxoutline to dictionary
for vp in viewPorts:
sheet = doc.GetElement(vp.SheetId)
view = doc.GetElement(vp.ViewId)
vbox = vp.GetBoxOutline()
viewPortList.append([sheet.SheetNumber, view.ViewName, vbox])
print(viewPortList)
Which works fine and prints the below (only portion of a long list)
[['A0.01', 'APPLICABLE CODES', <Autodesk.Revit.DB.Outline object at 0x000000000000060D [Autodesk.Revit.DB.Outline]>], ['A0.02', etc.]
But I want a dictionary instead. Any help would be appreciated. Thanks!
In your list example, you are appending to the list. In your dictionary example, you are creating a new dictionary each time (thus removing the data from previous iterations of the loop). You can do the equivalent of appending to it as well by just assigning to a particular key in the existing dictionary.
viewPortDict[view.ViewName] = {'sheetNum': sheet.SheetNumber, 'viewBox' : vbox}
Hi i have this function:
def company_runtime(company_name):
for well in all_wells:
well_runtime = {}
if well["groupName"].lower() == company_name.lower():
well_runtime.update({well["name"]: well["efficiency"]})
return well_runtime
And i want to get a dictionary with "names" and "efficiency" from the loop, if i enter a compay name as a parameter.
I am getting only the last element of the all_wells list that meet that condition.
what i am doing wrong?
Thanks in advance
Each time you go through the loop you are resetting the Dictionary to {} or empty thus it clears it out until the last time on exit. Move well_runtime = {} outside of the loop.
I have a function to create dictionary
def Bowler_creator (Name):
"""
This function will create the dictionaries for the batting player
"""
global bowler;
bowler = {
Name : { "number_of_overs":0.0,
"number_of_runs":0,
"number_of_wickets":0,
'economy_rate':0.0,
'Maiden overs':0
},
}
Current_Bowler = input("Enter the bowler's name\n");
Bowler_creator(Current_Bowler);
Bowler_creator('jafda');
My idea is that i will be calling this function like below so that new key with the same entry values will be created for this dictionary
So as per my idea, the dictionary should have created two elements with two keys Current_Bowler and jafda, but after I try to print the dictionary it´s returning the latest one only. Could you please let me know why my dictionary is getting overridden with a newer key?
You are replacing the dictionary with an entirely new dictionary each time.
You should create the dictionary once, then add keys:
bowler = {}
def Bowler_creator (Name):
bowler[Name] = {
"number_of_overs":0.0,
"number_of_runs":0,
"number_of_wickets":0,
'economy_rate':0.0,
'Maiden overs':0
}
Note: because the function no longer needs to assign a new object to bowler, you don't need to mark it as a global either. Assigning directly to the key modifies the global dictionary directly.
You are creating a new dictionary every time in the function Bowler_creator.
Try doing
bowler[Name] = { "number_of_overs":0.0,
"number_of_runs":0,
"number_of_wickets":0,
'economy_rate':0.0,
'Maiden overs':0
}
I am having trouble with a python class i wrote, the particular problem is in the parseData() function.
at the end of the function i have commented where the problem is. The problem is that when i finish the inner loop of the code towards the bottom of the parseData() function is run the value of self.listOfParsedWeatherData is correct, however once the scope falls out of the second loop the value of each element in self.listOfParsedWeatherData is a copy of the previous last element.
Basically when i check the value of the list within the scope of the second loop it would be something like [0, 1, 2, 3, 4, 5] but when i check the value of the same list outside of the second loop it it comes up as
[5, 5, 5, 5, 5, 5].
I am sure it has something to do with scopes or deep and shallow copies but I'm still fairly new to the python language and I'm not sure of some of the intricacies. Though i doubt the problem is something really complex.
Any help would be greatly appreciated the class is shown below and the object I'm inserting is a simple custom class that i wrote.
# imports
import pywapi # used to grab weather data from NOAA in a JSON format
import copy
from WeatherData import WeatherData # import custom weatherdata object
import pprint
pp = pprint.PrettyPrinter(indent=4) # set up pretty printer object
##
## Class used for grabing and parsing weather data from
## NOAA
##
class NOAAParser:
# initliazer for the NOAAParser class
def __init__(self):
# stores the list of json city data
self.listOfCityData = []
# A list of weatherData
self.listOfParsedWeatherData = []
##
## function to grab the weather and returns a JSON object of the weather data
##
## Parameters: self, dictionary of cities and their codes
##
def retrieveNOAAWeatherJson(self, cityCodes):
# loop through city codes and append them to a list of
cityData = []
# weather objects returned from pywapi
for key, value in cityCodes.iteritems():
cityData.append(pywapi.get_weather_from_noaa(value))
# set the list of city json data
self.listOfCityData = cityData
##
## This function parses the listOfCityData and returns a list
## of weatherData objects which can be displayed to the user
##
##
def parseData(self):
# check if the listOfCities has been populated
if not self.listOfCityData:
return False
else:
# create a new object of weather data
newWeatherData = WeatherData()
# loop over list and parse the data
for index in range(len(self.listOfCityData)):
# loop over the dictionary values in the list
for key, value in self.listOfCityData[index].iteritems():
# grab weather Description key: "weather" (String)
if key == "weather":
# print value
newWeatherData.weatherCondition = value
# grab the location key: "location" (String)
if key == "location":
# print value
newWeatherData.location = value
# grab temp key: "temperature_string" (String)
if key == "temperature_string":
# print value
newWeatherData.currentTemp = value
# grab Humidity key: "relative_humidity" (Int)
if key == "relative_humidity":
# print value
newWeatherData.humidity = value
# grab wind direction key: "wind_dir" (String)
if key == "wind_dir":
# print value
newWeatherData.windDirection = value
# grab last updated time key: "observation_time" (String)
if key == "observation_time":
# print value
newWeatherData.lastUpdated = value
# append the new weather data object to the list
self.listOfParsedWeatherData.append(newWeatherData)
## VALUE OF self.listOrParsedWeatherData is correct
## VALUE OF self.listOfParsedWeatherData is only the value of the last element
## of the previous self.listOfParsedWeatherData (incorrect)
# return success from the function
return True
This is happening because you only ever create a single instance of the WeatherData class, so you just keep updating that same one over and over again.
You just need to move the line newWeatherData = WeatherData() inside of your first for loop.
I have a dictionary carrying key:value however it only saves the last iteration and discards the previous entries where is it being reset ?? This is the output from the ctr of iterations and the length of the dictionary
Return the complete Term and DocID Ref.
LENGTH:6960
CTR:88699
My code:
class IndexData:
def getTermDocIDCollection(self):
...............
for term in terms:
#TermDocIDCollection[term] = sourceFile['newid']
TermDocIDCollection[term] = []
TermDocIDCollection[term].append(sourceFile['newid'])
return TermDocIDCollection
The piece of code you've commented out does the following:
Sets a value to the key (removing whatever was there before, if it existed)
Sets a new value to the key (an empty list)
Appends the value set in step 1 to the new empty list
Sadly, it would do the same each iteration, so you'd end up with [last value] assigned to the key. The new code (with update) does something similar. In the old days you'd do this:
if term in TermDocIDCollection:
TermDocIDCollection[term].append(sourceFile['newid'])
else:
TermDocIDCollection[term] = [sourceFile['newid']]
or a variation of the theme using try-except. After collections was added you can do this instead:
from collections import defaultdict
# ... code...
TermDocIDCollection = defaultdict(list)
and you'd update it like this:
TermDocIDCollection[term].append(sourceFile['newid'])
no need to check if term exists in the dictionary. If it doesn't, the defaultdict type will first call to the constructor you passed (list) to create the initial value for the key