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"])
Related
I need to extract the inner dictionary from outer list ie remove the outer square brackets of the list.
example:
myList =[{'a':'1','b':'2','c':'3'},{'d':'4','e':'5'}]
Desire output:
{'a':'1','b':'2','c':'3'},{'d':'4','e':'5'}
Please note that inner dictionaries can be of dynamic size.
Any help would be great.
Just accessing the list element by index.
myList =[{'a':'1','b':'2','c':'3'},{'d':'4','e':'5'}]
d = myList[0]
So if you have k dictionaries in the list you need to access all of them, but this will be tedious.
Iterate through the list like any other list iteration:
for i in myList:
i # i is your dictionary
"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"])
So I want to loop over a dictionary and a list simultaneously without them being nested.
What I really mean is:
for i,c in enumerate(dictionary) and for k in range(len(list)):
dictionary[c] = list[k]
So it basically loops over one dictionary and I can assign values to the dictionary with a list.
IIUC, you are trying to reassign existing keys to list values. This is something you can only do from python-3.7 onwards (or 3.6 if you use CPython). This can be done either through direct reassignment,
dictionary = dict(zip(dictionary, lst))
Or, if they are not the same length, and there are keys you want to preserve, use dict.update:
dictionary.update(dict(zip(dictionary, lst)))
Additionally, it is unwise to name variables after builtin objects (such as list).
zip is your friend
dictionary.update(zip(dictionary, lst))
I am reading items from a txt file into a list and then converting it into a dictionary as follows-
def getfeatures_into_list(inputfilename):
fid=open(inputfilename,"r")
dict_Lab_Features=defaultdict(int)
list1=[]
for line in fid:
list1.append(line.rstrip().lower())
list1=list(set(list1)) #Removing duplicates
c=0
for items in sorted(list1):
dict_Lab_Features[items]=c
c+=1
dict_Lab_Features=sorted(dict_Lab_Features.items(), key=operator.itemgetter(1))
print(dict_Lab_Features['Hello'])
I am getting error in the print statement
list indices must be integer,not str
Edit I want to sort the dict by value in ascending order.
In this line:
dict_Lab_Features=sorted(dict_Lab_Features.items(), key=operator.itemgetter(1))
you have reassigned dict_Lab_Features so that it is a list. This is because the output of sorted() is always a list. Naturally, a list cannot take a string as an index.
You should learn to think of dictionaries as inherently unsorted. There is such a thing as an OrderedDict for when you really need to keep track of insertion order, but for most purposes, a regular dict is fine. You just have to get into the habit of traversing the dictionary in the desired order, not worrying about whether the dictionary is stored in any kind of order.
The usual way to traverse a dictionary in sorted order is to just loop over the sorted keys, such as:
for key in sorted(dict_Lab_Features):
print dict_Lab_Features[key]
or
for key, value in sorted(dict_Lab_Features.items()):
print value
Or, if you want to loop over the sorted values,
for value in sorted(dict_Lab_Features.values()):
print value
You cannot sort a dict. Dicts are unordered mappings of elements.
Let's analyize the following line:
dict_Lab_Features=sorted(dict_Lab_Features.items(), key=operator.itemgetter(1))
From the documentation of sorted:
Return a new sorted list from the items in iterable.
So after that, dict_Lab_Features is a sorted list of key-value tuples. After that you try to index it with 'Hello'
print(dict_Lab_Features['Hello'])
Here you try to index that list with 'Hello', that's why you get the error list indices must be integer,not str
dict_Lab_Features stops being a dict when you call dict.items(). A dict.items() object cannot be addressed using string keys (it's really just a list of tuples [(key, value), ... ]).
Furthermore, "sorting" a dictionary you then intend to use by name doesn't make much sense either. Looks like you either need a collections.OrderedDict or you should skip ordering altogether
Up until now I have been using this code to uniquify (remove duplicates) from list in python:
my_list = list(set(my_list))
I now have a list of lists, I want to be able to remove duplicates from within the list of lists. For example:
(['possible-duplicate', 'random-data'], ['possible-duplicate', 'random-data'], ['possible-duplicate', 'random-data'])
I want to remove the whole sublist if possible-duplicate is a duplicate.
Can this be done?
Thanks
seen = set()
[sublist for sublist in my_list if sublist[0] not in seen and not seen.add(sublist[0])]
This happens to preserve order as well, which list(set(...)) does not.
Make a dictionary from your data:
data = (['possible-duplicate', '12345'],
['not-a-duplicate', '54321'],
['possible-duplicate', '51423'])
data_unique = dict(data)
Result is {'not-a-duplicate': '54321', 'possible-duplicate': '51423'}, or if you prefer a list of tuples, use date_unique.items(), which gives you [('not-a-duplicate', '54321'), ('possible-duplicate', '51423')].
Or for the more general case, where the sublists have more than two elements, you can use this
data_unique = dict((d[0], d) for d in data)
and then use data_unique.values() to reclaim the "uniquified" list.