"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"])
Related
I have a empty list of tuple and I wish to enter values inside that tuple.
The desired output is :
lst = [()] --> lst = [(1,2,'string1','string2',3)]
A tuple is, by definition, unchangable.
You may want to replace that tuple with a new one like this:
lst = [()]
lst[0] = ("item1", "item2")
In this way you are replacing the origina tuple with a new one with the desired items. If the tuple is not empty you can do:
lst[0] = (*lst[0], "new item")
Here you are unpacking the values of the old tuple (*lst[0] is equal to "item1", "item2" in this example) and adding new items.
Note that if you are working with variable data maybe tuple is not the best data structure to use in this case.
you can't, A tuple is a collection that is ordered and immutable.
though, you can create a new tuple with the same name
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']
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 trying to output some keys, for all indexes, e.g:
print results["result"][0]["name"]
prints out the first key with no problems, and so does [1], [2], etc. I want to be able to print all indexes, for the value "name". I'm sure it uses a for loop, and tried several methods, but have failed.
How can I print the results for all indexes, not just 1?
Assuming results['result'] is a list, use a for loop to iterate over the items in that list:
for item in results['result']:
print(item['name'])
So assuming results is a dictionary-like object, results["result"] is a list containing dictionary-like elements, where these elements have a key "name",
You could use a list comprehension:
print([e["name"] for e in results["result"])
If results["result"] is a dict, this would be:
print([e["name"] for e in results["result"].values())
# or, less efficiently
print([results["result"][e]["name"] for e in results["result"])
Just join the list comprehension with newlines:
print '\n'.join(i["name"] for i in results["result"])
I have a dictionary that needs its values to be 2D lists. I am having trouble adding these second values to a key. I have two lists, the first a list of values then a list of keys that is composed of additional lists.
So far I have this code:
for i in range(len(keyList)):
if keyList[i] in theInventory:
value = theInventory[keyList[i]]
value.append(valueList[i])
theInventory[keyList[i]] = value
else:
theInventory[keyList[i]] = valueList[i]
The problem is that the output has a list of entries for the first added to the list then it has the lists I am looking to add to my dictionary.
Like so:
[value, value, value, [list], [list]]
How do I make the first entry be entered into the dictionary as its own list?
Use extra [] around valueList[i]:
theInventory[keyList[i]] = [valueList[i]]
You can simplify your code as follows. The append() method mutates the list, so there is no need to assign the result of the append back the theInventory. Further there is no need to use value at all, instead you can just directly append to the item in the dictionary.
for i in range(len(keyList)):
if keyList[i] in theInventory:
theInventory[keyList[i]].append(valueList[i])
else:
theInventory[keyList[i]] = [valueList[i]]