i have below list, trying to pull the value of the list pair, example i need to know what is the average_buy_price from the list.
[{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
currently it is giving error.
TypeError: list indices must be integers or slices, not str
the above output is coming from system, i need to select only the value which i need. example ( 'average_buy_price') need to get the output of the value. '6755.03
one thing i have notice is that, it is starting with [ and closing with ] , for testing i just copied from { to } i am able to pull the value, looks like some problem with syntax when i am using. required help.
In you list there is a single dictionary. To access average_buy_price from the dict try:
test_list = [{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
print(test_list[0].get('average_buy_price')) # output 6755.03
Yes, as long as you have the square brackets, it's a list, and so it cannot be indexed with a string.
Get rid of the square brackets (and retain only the curly braces). It is then no longer a list, but a dictionary, which can be indexed with the string key value.
Each element of your list is actually a dictionary. So, iterate through the list, then get the key, value pair.
myList= [{'enabled': True, 'total_buy_quantity': 45, 'average_buy_price': '6755.03'}]
for d in myList:
for k, v in d.items():
print(k,': ',v)
Output:
enabled : True
total_buy_quantity : 45
average_buy_price : 6755.03
You have a list containing a single dictionary. If you want to access the elements of the dictionary, first index the list: test_list[0]['average_buy_price']
Related
i have a json data https://steamcommunity.com/id/RednelssGames/inventory/json/730/2
need get names of all the items
r = requests.get('https://steamcommunity.com/id/RednelssGames/inventory/json/730/2')
if r.json()['success'] == True:
for rows in r.json()['rgDescriptions']:
print(rows['market_hash_name'])
getting error string indices must be integers
Change the for-loop as follows:
for rows in r.json()['rgDescriptions'].values():
print(rows['market_hash_name'])
By iterating over a dictionary like you did, you get the keys and not the values (rows). If you want to iterate over the values, you have to iterate over the return value of dict.values().
From the link you provided:
"rgDescriptions":{"4291220570_302028390":
rgDescriptions doesn't return an array, but an object (a dictionary, in this case) (notice the opening curly brace ({) rather than a regular square brace ([)).
By using for rows in r.json()['rgDescriptions']: you end up iterating over the dictionary's keys. The first key of the dictionary seems to be "4291220570_302028390", which is a string.
so when you do print(rows['market_hash_name']), you're attempting to access the 'market_hash_name' "index" of your rows object, but rows is actually a string, so it doesn't work.
"trip" is a list of dictionaries. In this instance, the key "trip_block" only appears in the 6th dictionary. Why doesn't this work:
trip[:]['trip_block']
TypeError: list indices must be integers or slices, not str
But this does work and returns the value:
trip[5]['trip_block']
Since that key appears in different indexes, I would really like to search for it by using trip[:]. I'm trying to use this in an if statement:
if trip[:]['trip_block']:
trip[:] is a list. Trying to index it like a dictionary isn't going to work. If you want a list of all the values that dictionaries that contain 'trip_block' try:
[d['trip_block'] for d in trip if 'trip_block' in d]
the [:] is a slicing, and what it does depends on the type of trip. If trip is a list, this line will create a shallow copy of the list. For an object of type tuple or a str, it will do nothing (the line will do the same without [:]), and for a (say) NumPy array, it will create a new view to the same data.
You could use the following instead:
trip = [
{"name": "name1", "trip_block__": 10},
{"name": "name2", "trip_block_": 5},
{"name": "name3", "trip_block": 7}
]
res1 = next(item for item in trip if 'trip_block' in item.keys())
print(res1)
res2 = list(filter(lambda trip_block: 'trip_block' in trip_block.keys(), trip))
print(res2)
The first method is finding the dict that has the desired key.
The second one the filter the dict that consist the desired key
My suggestion would be to loop through your list. The [:] variant just grabs all of the dictionaries in the list. Take a look at this and see if it will work for you:
for dictionary in trip: #loop through list of dicts
if 'trip_block' in dictionary.keys(): #check if key is in this dict
print(dictionary['trip_block'])
break #end loop, don't use break if there's more than one dict with this key and you need them all
trip[:] means you get just a copy of the whole list
You need to iterate over the list...
and because it appears in different indexes you need to store it again in an list.
You can use list comprehension like
trip_block_items = [item["trip_block"] for item in trip if "trip_block" in item]
or a simply a for loop
trip_block_items = []
for item in trip:
if "trip_block" in item:
trip_block_items.append(item["trip_block"])
I am trying to do something pretty simple but cant seem to get it. I have a dictionary where the value is a list. I am trying to just sum the list and assign the value back to the same key as an int. Using the code below the first line doesn't do anything, the second as it says puts the value back but in a list. All other things ive tried has given me an error can only assign iterable. As far as i know iterables are anything that can be iterated on such as list and not int. Why can I only use iterable and how can i fix this issue ? The dict im using is here (https://gist.github.com/ishikawa-rei/53c100449605e370ef66f1c06f15b62e)
for i in dict.values():
i = sum(i)
#i[:] = [sum(i) / 3600] # puts answer into dict but as a list
You can use simple dictionary comprehension if your dict values are all lists
{k:sum(v) for k, v in dict.items()}
for i in dikt.keys():
dickt[i] = sum(dict[i]))
btw, dict is a type. best not to use it as a variable name
my_dict = dict([(1,'apple'), (2,'ball')])
when I print my_dict the output is
{1: 'apple', 2: 'ball'}
How it's working?
I am new to python Please explain this
Thanks in advance!
Dictionary is data structure in Python. Think about it as an unordered(after python3.7 can be ordered) set of key: value pairs.
The values of a dictionary can be of any type, keys must be of an immutable data type such as strings, numbers, or tuples.
In your command, dict() used as constructor and values([(1,'apple'), (2,'ball')]) is an iterable object.
Each item in the iterable is itself an iterable with exactly two objects. The first object of each item becomes a key in the new dictionary, and the second object the corresponding value.
Here is different representation of your example:
list_of_tuples = [(1,'apple'), (2,'ball')]
in order to create a dictionary, program will need to iterate thru the each value in the list_of_tuples
thats why you can use dict() constructor to do it, like so:
my_dict = dict(list_of_tuples)
Note that if a key occurs more than once, the last value for that key becomes the corresponding value in the new dictionary.
When you create a dictionary you do with curly brackets, {}, with the keys and values separated by colons, :. Here's an example
my_dict = {
1 : 'apple',
2 : 'ball'
}
You can index this dictionary with square brackets as you've done in the question.
When you call print on this dictionary it prints it out in a similar fashion with the key followed a colon and the value, all encompassed within curly brackets.
{1: 'apple', 2: 'ball'}
If you would like to print a particular value in the dictionary you do so as follows
print my_dict[1]
This would print out the value associated with 1 in the dictionary which in our example is
apple
I'm I need to slice the leading character off the valued a dictionary - but only if the length of the value is greater than 1. Currently I'm doing this with a dictionary comprehension:
new_dict = {item[0]:item[1][1:] for item in old_dict if item.startswith('1')}
but I don't know how to modify this so that keys of length one are left alone.
The keys are the codewords of a Huffman code, and so start with '0' or '1'.
An example code is:
code = {'a':'0', 'b':'10', 'c':'110', 'd':'111'}
The above code works fine for 'b','c','d' but fails for 'a' (this is intensional - it's a unit test).
How do I correctly modify the above example to pass the test?
The nature of a comprehension is that it builds a new object iteratively, so you if you want every key in the original object old_dict to have a corresponding key in new_dict, you simply have to process every key.
Also, you say "I need to slice the leading character off the keys a dictionary", but the code you give slices the leading characters off the values. I assume you mean values. I suggest the following:
new_dict = {key:(value[:1] if len(value) > 1 else value) for key,value in old_dict.iteritems()}
Apart from using sequence assignment to make the iteration a bit clearer, I've used the if expression (equivalent to ternary operator in c-like languages) to incorporate the condition.
I've also dropped your original if clause, because I don't understand you to want to skip values starting with '1'.
I'm not sure which variable is where but you could do something along these lines.
new_dict = { item[0]:item[1][1] if len(item[1]) > 1 else item[0]:item[1] for item in old_dict if item.startswith('1') }
If I understand your question correctly, you can accomplish it with this:
new_dict = {k:v[len(v)>1:] for k,v in old_dict.items()}
v[len(v)>1] will return the key if it is only 1 character, and it will strip off the leading character if it is more than one character
I'm not sure what you are trying to accomplish with if item.startswith('1') is a qualifier for your list comprehension but if you need it you can add it back on. May need to make it v.startswith('1') though.