I'm trying to add every value under "title" from a dictionary to a list but i always get KeyError: 'title'.
list = []
q = input("Search:")
search = SearchVideos(q, mode = 'dict')
dictt = (search.result())
print(dictt)
for i in dictt:
list.append(dictt['title'])
you have a few problems here.
First, you're not accessing the right value. It looks like dictt has only one key: search_result and you should iterate on it's value.
In addition, list.append(value) will not add the value to a list. you need to make a list and then do new_list.append(value).
lastly you didn't use i in your loop.
It should look like this:
new_list = []
for item in dictt['search_result']:
new_list.append(item['title'])
Related
I am trying to find a way to remove duplicates from a dict list. I don't have to test the entire object contents because the "name" value in a given object is enough to identify duplication (i.e., duplicate name = duplicate object). My current attempt is this;
newResultArray = []
for i in range(0, len(resultArray)):
for j in range(0, len(resultArray)):
if(i != j):
keyI = resultArray[i]['name']
keyJ = resultArray[j]['name']
if(keyI != keyJ):
newResultArray.append(resultArray[i])
, which is wildly incorrect. Grateful for any suggestions. Thank you.
If name is unique, you should just use a dictionary to store your inner dictionaries, with name being the key. Then you won't even have the issue of duplicates, and you can remove from the list in O(1) time.
Since I don't have access to the code that populates resultArray, I'll simply show how you can convert it into a dictionary in linear time. Although the best option would be to use a dictionary instead of resultArray in the first place, if possible.
new_dictionary = {}
for item in resultArray:
new_dictionary[item['name']] = item
If you must have a list in the end, then you can convert back into a dictionary as such:
new_list = [v for k,v in new_dictionary.items()]
Since "name" provides uniqueness... and assuming "name" is a hashable object, you can build an intermediate dictionary keyed by "name". Any like-named dicts will simply overwrite their predecessor in the dict, giving you a list of unique dictionaries.
tmpDict = {result["name"]:result for result in resultArray}
newArray = list(tmpDict.values())
del tmpDict
You could shrink that down to
newArray = list({result["name"]:result for result in resultArray}.values())
which may be a bit obscure.
I may be missing something fundamental here but consider the following:
graph=nx.read_graphml('path here...')
dDict=dict(nx.degree_centrality(graph)) #create dict
lDict=dict(nx.load_centrality(graph))
new_lists=[dDict,lDict]
for i in new_lists:
print().... #how to get variable name i.e. dDict
how do i iterate through the list of dicts so that when i do a print it returns me the variable name the dict equals i.e. i want to be able to retrieve back 'dDict' and 'lDict'?I do not want a quick hack such as
dDict['name'] = 'dDict'
Any ideas..?
EDIT: the reason i want to do this is so that i can append these centrality measures to a dataframe with new column name i.e.:
for idx in range(len(new_lists)):
for i in range(len(df)):
rowIndex = df.index[i]
df.loc[rowIndex, idx] = new_lists[idx][rowIndex] #instead of idx how do i dynamically name the column according to the list item name.
You can iterate over globals() and get the variable name of the object that matches the content you are looking for.
More info on https://docs.python.org/3/library/functions.html?highlight=globals#globals
However, this is a rather cumbersome trick, you should not do that! Rather, redesign your software so you don't have to look for the variable names in the first place.
def get_var_name_of(x):
return [k for k,v in globals().items() if v==x][0]
dDict = {1:'asd'}
lDict = {2:'qwe'}
new_list=[dDict,lDict]
for d in new_list:
print(get_var_name_of(d))
dDict
lDict
I have a list which grows and shrinks in a for loop. The list looks like following :- . With every element inside list of list i want to associate it to a separate dictionary.
list123 = [[1010,0101],[0111,1000]]
In this case I want to create 4 dictionary with the following name
dict1010 = {}
dict0101 = {}
dict0111 = {}
dict1000 = {}
I tried following loop
for list1 in list123:
for element in list1:
dict + str(element) = dict()
This is the error i am getting
SyntaxError: can't assign to literal
while you can dynamically create variables, unless there is an overwhelming need to do that use instead a dictionary of dictionary witch key is the name you want, like this
my_dicts=dict()
for list1 in list123:
for element in list1:
my_dicts["dict" + str(element)] = dict()
and to access one of them do for example my_dicts["dict1010"]
You can uses globals() function to add names to global namespace like this
for list1 in list123:
for element in list1:
globals()["dict"+str(element)] = {}
this will add variables with the names you want as if you created them using dictx={} also numbers that begins with 0 won't convert well using str() so you should make your list a list of strings
First of all, I must say that you shouldn't do this. However, if you really want to, you can use exec.
If you really want to do this, you could use exec:
list123 = [[1010,0101],[0111,1000]]
for list1 in list123:
for element in list1:
var = 'dict' + str(element)
exec(var + ' = dict()')
the current code I have is category1[name]=(number) however if the same name comes up the value in the dictionary is replaced by the new number how would I make it so instead of the value being replaced the original value is kept and the new value is also added, giving the key two values now, thanks.
You would have to make the dictionary point to lists instead of numbers, for example if you had two numbers for category cat1:
categories["cat1"] = [21, 78]
To make sure you add the new numbers to the list rather than replacing them, check it's in there first before adding it:
cat_val = # Some value
if cat_key in categories:
categories[cat_key].append(cat_val)
else:
# Initialise it to a list containing one item
categories[cat_key] = [cat_val]
To access the values, you simply use categories[cat_key] which would return [12] if there was one key with the value 12, and [12, 95] if there were two values for that key.
Note that if you don't want to store duplicate keys you can use a set rather than a list:
cat_val = # Some value
if cat_key in categories:
categories[cat_key].add(cat_val)
else:
# Initialise it to a set containing one item
categories[cat_key] = set(cat_val)
a key only has one value, you would need to make the value a tuple or list etc
If you know you are going to have multiple values for a key then i suggest you make the values capable of handling this when they are created
It's a little hard to understand your question.
I think you want this:
>>> d[key] = [4]
>>> d[key].append(5)
>>> d[key]
[4, 5]
Depending on what you expect, you could check if name - a key in your dictionary - already exists. If so, you might be able to change its current value to a list, containing both the previous and the new value.
I didn't test this, but maybe you want something like this:
mydict = {'key_1' : 'value_1', 'key_2' : 'value_2'}
another_key = 'key_2'
another_value = 'value_3'
if another_key in mydict.keys():
# another_key does already exist in mydict
mydict[another_key] = [mydict[another_key], another_value]
else:
# another_key doesn't exist in mydict
mydict[another_key] = another_value
Be careful when doing this more than one time! If it could happen that you want to store more than two values, you might want to add another check - to see if mydict[another_key] already is a list. If so, use .append() to add the third, fourth, ... value to it.
Otherwise you would get a collection of nested lists.
You can create a dictionary in which you map a key to a list of values, in which you would want to append a new value to the lists of values stored at each key.
d = dict([])
d["name"] = 1
x = d["name"]
d["name"] = [1] + x
I guess this is the easiest way:
category1 = {}
category1['firstKey'] = [7]
category1['firstKey'] += [9]
category1['firstKey']
should give you:
[7, 9]
So, just use lists of numbers instead of numbers.
I have 2 lists
old_name_list = [a-1234, a-1235, a-1236]
new_name_list = [(a-1235, a-5321), (a-1236, a-6321), (a-1234, a-4321), ... ]
I want to search recursively if the elements in old_name_list exist in new_name_list and returns the associated value with it, for eg. the first element in old_name_list returns a-4321, second element returns a-5321, and so on until old_name_list finishes.
I have tried the following and it doesn't work
for old_name, new_name in zip(old_name_list, new_name_list):
if old_name in new_name[0]:
print new_name[1]
Is the method I am doing wrong or I have to make some minor changes to it? Thank you in advance.
Build a dict() based on your second list, and lookup in that.
old_name_list = ["a-1234", "a-1235", "a-1236"]
new_name_list = [("a-1235", "a-5321"), ("a-1236", "a-6321"), ("a-1234", "a-4321") ]
d = dict(new_name_list)
for n in old_name_list:
print d[n]
You do need to put quotes around strings like "a-1234".
Using a dictionary may be the best way to do this.
old_name_list = ['a-1234', 'a-1235', 'a-1236']
new_name_list = [('a-1235', 'a-5321'), ('a-1236', 'a-6321'), ('a-1234, a-4321')]
mapping = dict(new_name_list)
values = [mapping[item] if item in mapping for item in old_name_list]
print values
Use this:
found_items = [item[1] for item in new_name_list if item[0] in old_name_list]