Extract info from a dict turned list - python

I have a list that has been extracted from a dictionary and the first element of the new list looks like this:
The total # of elements in my list are 4200; I was wondering how would I extract the 'uri' of each individual element and place it into a new list.

Quick way using list comprehension:
[elem['nft_metadata']['data']['uri'] for elem in result['minted_nfts']]

Related

Check if elements list are in column DataFrame

Objective: I have a list of 200 elements(urls) and I would like to check if each one is in a specific column of the Dataframe. If it is, I would like to remove the element from the list.
Problem: I am trying a similar solution by adding to a new list the ones that are not there but it adds all of them.
pruned = []
for element in list1:
if element not in transfer_history['Link']:
pruned.append(element)
I have also tried the solution I asked for without success. I think it's a simple thing but I can't find the key.
for element in list1:
if element in transfer_history['Link']:
list1.remove(element)
When you use in with a pandas series, you are searching the index, not the values. To get around this, convert the column to a list using transfer_history['Link'].tolist(), or better, convert it to a set.
links = set(transfer_history["Link"])
A good way to filter the list is like this:
pruned = [element for element in list1 if element not in links]
Don't remove elements from the list while iterating over it, which may have unexpected results.
Remember, your syntax for transfer_history['Link'] is the entire column itself. You need to call each item in the column using another array transfer_history['Link'][x]. Use a for loop to iterate through each item in the column.
Or a much easier way is to just check if the item is in a list made of the entire column with a one liner:
pruned = []
for element in list1:
if element not in [link for link in transfer_history['Link']]:
pruned.append(element)
If the order of the urls doesn't matter, this can be simplified a lot using sets:
list1 = list(set(list1) - set(transfer_history['Link']))

Insert element in list of list from list

Want to insert list elements in list of list such that first element of list should be inserted to first index of first list of list then second element of list of list to first element of 2nd list of list and so on...
For eg.
lst_of_lst = [[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]]
list = ['a','b','c','d']
output - lst_of_lst=[['a',1,2,3,4]['b',5,6,7,8]['c',9,10,11,12]['d',13,14,15,16]]
All you need to do is just iterate over your the list you want to insert the items from and just insert the respective item at 0th position.
It can be done as follows:
for i in range(len(list)):
lst_of_lst[i].insert(0, list[i])
That's it!
Also, you missed , in defining lst_of_lst, it will give you error. And also it is not a good way to name any variable or data structure a name of data type. Like you did for list array. You can change it to _list if you want.
Little trickery for fun/speed:
lst_of_lst = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
list = ['a','b','c','d']
for L, L[:0] in zip(lst_of_lst, zip(list)):
pass
print(lst_of_lst)
Try it online!

Get item from sublist with another sublist containing indexes

I am struggling with sublists, I would like to get items from list at indexes given in index_list where these indexes are also in sublist. I would like to also keep the structure. What is the best method to do that? Should I use zip() ?
list = [['a','b','c'],['a','b','c','d'],['a','b','c']]
index_list = [[0,2],[1,2,3],[1,2]]
For each sublist, then for each index get the corresponding value (also don't use list built-in name as variable name)
results = [[values[sub_idx][item] for item in sublist] for sub_idx, sublist in enumerate(index_list)]
CODE DEMO

How to add elements of a list to existing dictionary based on key?

I have an iterator for creating multiple lists. I need to keep adding the generated list to a dictionary dict1 based on the key value k:
some value here = k
for a in jsoncontent:
list1.append(a["Value"])
dict1.setdefault(k, []).append(list1)
Right now I get:
{k:[[10,11],[12,32,6],[7,4]]}
But I need:
{k:[10,11,12,32,6,7,4]}
How do I merge these lists?
It sounds like you want extend versus append. extend inserts the contents of the list at the end of the list, while append insets its argument, a list in this case. See https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types

Sorting list of dictionaries according to specific order

I am using Python 2.6 and I have two data stores. Querying the first one returns a list of document IDs in a specific order. I look up all the documents at once in the second data store using these IDs, which returns a list of dictionaries (one for each doc), but not in the same order as the original list. I now need to re-sort this list of dictionaries so that the documents are in the order that their IDs were in the first list. What's the best way of doing this?
Don't.
Move your "list of dictionaries (one for each doc), but not in the same order as the original list" into a dictionary.
This new dictionary-of-dictionaries has the matching key.
Then go through your first list in it's order and find items in the dictionary-of-dictionaries that match.
some_list= query_data_store_1()
some_other_list= query_data_store_2( some_list )
dict_of_dict = dict( (d['key'], d) for d in some_other_list )
for item in some_list:
other_item = dict_of_dict[ item['key'] ]
# Now you have item from the first list matching item from the second list.
# And it's in order by the first list.
You could build a separate dictionary mapping ids to positions and use that to order the documents:
ids = ...
positions = {}
for pos, id in enumerate(ids):
positions[id] = pos
docs = ...
docs.sort(key=lambda doc: positions[doc['id']])
The best (and general) solution seems to be given here: reordering list of dicts arbitrarily in python

Categories