i got timestamp returned as a tuple from rrd database i.e. info variable will contain this
[(38177492.733055562,
38177482.886388876),(39370533.190833323, 40563588.018611118)]
inside my code i am converting tuple (38177492.733055562,38177482.886388876) intto list using
list function after that i am accessing element using "index" variable and when i am passing this value to fromtimestamp function it is asking me the "float" value so how can i convert list object into float primitive data type ? following is the whole code
def hello(request):
info = rrdtool.fetch('hello/test.rrd','AVERAGE','-r','3600','-s','1298264400','-e','1298350800')
datalist = list()
for index in range(0,len(info)):
val = list(info[index])
dt_obj = datetime.fromtimestamp(float(val[index]))
str=dt_obj.strftime("%d-%m-%Y %H:%M:%S")
datalist.append(str)
data = simplejson.dumps(info, indent=4)
return HttpResponse(data,mimetype='application/javascript')
i am getting following error
a float is required
after changing code to for index in range(0,len(info)): i am getting following error
invalid literal for float(): Out
What you're doing doesn't make much sense, I'm afraid - index is an index into the info list, not into val, which is one of the tuples in that list.
Also, you don't need to convert the list into a tuple in order to access an element of the tuple.
Your indentation is broken in the line where the loop starts, and also when you outdent to return a json version of info.
To work out your problem, you could start by printing val, val[index] and type(val[index]) on the line before your error to check that they are what you're expecting them to be - clearly they're not from the error you get.
Also, you don't need to use the index into the info list at all, you could iterate over the values in the list with:
for val in info:
# I'm not sure if you want both values in the tuple here or just one...
print >> sys.stderr, "val =", val
dt_obj = datetime.fromtimestamp(val[0])
str=dt_obj.strftime("%d-%m-%Y %H:%M:%S")
datalist.append(str)
Related
So I have a json file which contains role ids (a dictionary named roles),with a key (which is the name of the role) and each key has the role's id as it's value
Looks something like this:
{"Ban": ["694175790639743076"], "Muted": ["692863646543380590"]}
I mostly just need the ids from the json
using something like roles['Muted'] or roles.get('Muted') gives me ['692863646543380590']:
Muted=roles.get('Muted')
print(Muted)
the functions take integers,so I have to remove [' from the output and get this: 692863646543380590
slicing just gives me [] no matter what slicing I use:
work=boost1[2:20] *or any other slice*
print(work)
gives out "[]"
why is slicing just not working here? and how do I fix this??
first of all roles['Muted'] is a list, if you want just first element then get it with 0 index then try using int() for converting it to Integer:
Muted=int(roles.get('Muted')[0]) # or Muted=int(roles['Muted'][0])
Muted will be:
692863646543380590
Try this -
work = int(boost1[0]) #fetching the first element of list and converting it into int
I need to make a function that updates tuples in a list of tuples. The tuples contain transactions, which are characterised by ammount, day, and type. I made this function that should completely replace a tuple with a new one, but when I try to print the updated list of tuples I get the error:
TypeError: tuple indices must be integers or slices, not str
The code:
def addtransaction(transactions, ammount, day, type):
newtransactions = {
"Ammount": ammount,
"Day": day,
"Type": type
}
transactions.append(newtransaction)
def show_addtransaction(transactions):
Ammount = float(input("Ammount: "))
Day = input("Day: ")
Type = input("Type: ")
addtransaction(transactions, ammount, day, type)
def show_all_transaction(transactions):
print()
for i, transaction in enumerate(transactions):
print("{0}. Transaction with the ammount of {1} on day {2} of type: {3}".format(
i + 1,
transaction['Ammount'], ; Here is where the error occurs.
transaction['Day'],
transaction['Type']))
def update_transaction(transactions): ; "transactions" is the list of tuples
x = input("Pick a transaction by index:")
a = float(input("Choose a new ammount:"))
b = input("Choose a new day:")
c = input("Choose a new type:")
i = x
transactions[int(i)] = (a, b, c)
addtransaction(transactions, 1, 2, service)
show_all_transaction(transactions)
update_transaction(transactions)
show_all_transaction(transactions)
A tuple is basically only a list, with the difference that in a tuple you cannot overwrite a value in it without creating a new tuple.
This means you can only access each value by an index starting at 0, like transactions[0][0].
But as it appears you should actually use a dict in the first place. So you need to rewrite update_transaction to actually create a dict similar to how addtransaction works. But instead of adding the new transaction to the end you just need to overwrite the transaction at the given index.
This is what update_transaction already does, but it overwrites it with a tuple and not a dict. And when you print it out, it cannot handle that and causes this error.
Original answer (Before I knew the other functions)
If you want to use strings as indexes you need to use a dict. Alternatively you can use namedtuple which are like tuples but it also has an attribute for each value with the name you defined before. So in your case it would be something like:
from collections import namedtuple
Transaction = namedtuple("Transaction", "amount day type")
The names given by the string used to create Transaction and separated by spaces or commas (or both). You can create transactions by simply calling that new object. And accessing either by index or name.
new_transaction = Transaction(the_amount, the_day, the_type)
print(new_transaction[0])
print(new_transaction.amount)
Please note that doing new_transaction["amount"] will still not work.
This is not a generic answer, I'll just mention it if someone bumps into the same problem.
As stated before, tuples are addressed by integer e.g. my_tuple[int] or slice my_tuple[int1:int2].
I ran into trouble when I ported code from Python2 to Python3. The original code used somthing like my_tuple[int1/int2], this worked in Python2 since division int/int results in int.
in Python3 int/int results in a floating point number.
I had to fix the code to my_tuple[int1//int2] to get the python2 behavior.
I have a tuple like: t= ({'count': 5L},)
Here i don't want to use for loop but want to get value as 5.Then how can i do it?
I tried with coverting to string then using JSON.
import json
s = str(t)
d = json.loads(s)
I got error:ValueError: No JSON object could be decoded
And winded up with no result.
I want to get the value of count as integer 5 & store in a variable.
Anyone having any idea?
No need to use Json since it is already your tuple is already a Python data structure.
If you know the index of the item in the tuple, and you know the keyname you can access it directly using:
t = ({'count': 5L},)
value = int(t[0]['count'])
I'm using the Temboo Twitter API for Python to download tweets. I want to interpret them but am having trouble pulling out certain values. It returns each tweet in JSON. I want to take certain items out of the JSON and pass them over for further use (favorite_count in the example below). print (json.loads(array)) works fine but the following line print (data['favorite_count']) does not and returns and error list indices must be integers, not str. Giving an integer value just returns and out of range index error.
Would really appreciate a solution to extracting a certain section from the JSON list.
homeTimelineResults = homeTimelineChoreo.execute_with_results(homeTimelineInputs)
if __name__ == "__main__":
array = homeTimelineResults.get_Response()
data = json.loads(array)
print (json.loads(array))
print (data['favorite_count'])
From the error you are getting, I would guess that data is a list, not a dictionary. What you could do then is something along these lines:
import collections
homeTimelineResults = homeTimelineChoreo.execute_with_results(homeTimelineInputs)
if __name__ == "__main__":
array = homeTimelineResults.get_Response()
data = json.loads(array)
if data and isinstance(data, collections.Iterable) and not isinstance(data, (str, bytes)):
result = data.pop(0)
print(result['favorite_count'])
Basically we are checking that data is indeed a list or tuple or something you can iterate over (but not a string or a sequence of bytes) and that it is not empty. This is the meaning of the if statement after data = json.loads(array).
If that is indeed the case, we pop the first element and - assuming that it is a dictionary - access its 'favorite_count' key. Of course this assumption is pretty dangerous and one should be a bit more careful and check first :-)
So I have a list of strings I want to make = 999
with open ("Inventory.txt", 'r') as i:
for items in i:
item = GetItemID(items)
PositionOfItems[items]=HERO_INVENTORY_POS
HERO_INVENTORY_POS is = 999, but I get the error displayed above, if I'm missing anything else require please tell me.
This is the code I used for spawning an item so I kinda just tried to recreate that.`
ItemRequest = input("Which item would you like?").upper()
for i in ItemList:
if i == ItemRequest:
ItemRequest = GetItemID(ItemRequest)
PositionOfItems[ItemRequest]=HERO_INVENTORY_POS`
If PositionOfItems is a list, then items needs to be in an integer. Right now, it's a string, because you're reading it from a file.
Try:
PositionOfItems[int(items)]=HERO_INVENTORY_POS
Alternatively, maybe you intended to index the list with item and not items? In which case you should do
PositionOfItems[item]=HERO_INVENTORY_POS
Depending in how you defined PositionOfItems
In your line of code
PositionOfItems[items]=HERO_INVENTORY_POS
You are treating it as a dictionary instead of a list, where items is the key and HERO_INVENTORY_POS is the value. When I tried reproducing your code snippet(below), my error was that the dictionary was not defined as empty before its use, and if defined as a list I received the TypeError: list indices must be integers, not str.
with open("test.txt", 'r') as f:
dict = {} #This line
for item in f:
dict[item] = 999
print item,
If you have assigned PositionOfItems as a list, then the issue is that you would be referring to indexes that have not been defined (or at least not show in your code here) and are attempting to reference them with a string (items) instead of an integer. (Giving you the TypeError)