Related
I am trying to get movies by genres from tmdb movie dataset by converting it into json.
There should be multiple entries for a specific genre like 'adventure', but all i get to see is the last record and seems like the previous records are getting overwritten. I have verified this by adding a print statement in the if statement and the details are showing up in the console but somehow getting overwritten.
Any help would be appreciated. Thanks!!
final_list = []
for i in range(1,1000):
if genre_name in data[str(i)]['genres']:
movie_dict["Title"] = data[str(i)]['title']
movie_dict["Language"] = data[str(i)]['original_language']
final_list = [movie_dict]
return final_list
There are two obvious problems. You redefine final_list in the loop and you return during the first loop.
Fixing that will give you something like this:
def myfunction(data, genre_name):
movie_dict = {}
final_list = []
for i in range(1,1000):
if genre_name in data[str(i)]['genres']:
movie_dict["Title"] = data[str(i)]['title']
movie_dict["Language"] = data[str(i)]['original_language']
final_list.append(movie_dict)
return final_list
Now there is another, more subtle problem. You always add the same dictionary to the list.
To give an example:
d = {}
l = []
for i in range(5):
d['x'] = i ** 2
l.append(d)
print(l)
Now l contains the same dictionary 5 times and this dictionary will have the content from the last iteration of the loop: [{'x': 16}, {'x': 16}, {'x': 16}, {'x': 16}, {'x': 16}]. To fix this you have to create the dictionary in the loop, so in your code you have to move movie_dict = {} to an appropriate place:
def myfunction(data, genre_name):
final_list = []
for i in range(1,1000):
if genre_name in data[str(i)]['genres']:
movie_dict = {}
movie_dict["Title"] = data[str(i)]['title']
movie_dict["Language"] = data[str(i)]['original_language']
final_list.append(movie_dict)
return final_list
Now some more advanced stuff. I assume data is a dictionary since you use a string for indexing. If you're not limited to 1000 entries but want to access all the values in the dictionary you can loop over the dictionaries values:
def myfunction(data, genre_name):
final_list = []
for entry in data.values():
if genre_name in entry['genres']:
movie_dict = {}
movie_dict["Title"] = entry['title']
movie_dict["Language"] = entry['original_language']
final_list.append(movie_dict)
return final_list
Now let us create the dictionary on the fly in the call to append.
def myfunction(data, genre_name):
final_list = []
for entry in data.values():
if genre_name in entry['genres']:
final_list.append({'Title': entry['title'], 'Language': entry['original_language']})
return final_list
This can be rewritten as a list comprehension:
def myfunction(data, genre_name):
return [{'Title': entry['title'], 'Language': entry['original_language']} for entry in data.values() if genre_name in entry['genres']]
That's all.
Try using final_list.append(movie_dict).
Bro you were actually actually returning the list after each value was added try this way and it will not overwrite it. The main reason is that you were returning the list in the for loop and everytime the loop run it save new dictionary in the list and remove the old one
final_list = []
for i in range(1,1000):
if genre_name in data[str(i)]['genres']:
movie_dict["Title"] = data[str(i)]['title']
movie_dict["Language"] = data[str(i)]['original_language']
final_list.append(movie_dict)
return final_list
I did tried but its saying object is not iterable can anybody fix it?
I actually want to convert list into nested dictionary where year will be my main key
a = ['1980', '1982', '1985', '1986']
b = ['Alex', 'Bob', 'John', 'David']
c = [9.99, 8.55, 7.66, 6.66],[5,7.5,8.5,9,5],[7.5,8.5,9,5],[7.5,8.5,9]
dic = dict(zip(*a,*b,*c))
Output I needed below.
{'1980':{'Alex':9.99,'Bob':8.5,'John':7.6,'David':6.66},'1982':{'Alex':5,'Bob':7.5,'John':8.5,'David':9} …….. So on for every year which is main key.
Thanks for the help
final_dict = {}
year_num = 0
for year in a:
final_dict[year] = {}
person_num = 0
for name in b:
final_dict[year][name]=c[person_num+(4*year_num)]
person_num+=1
year_num+=1
That should work
I am having trouble converting a 2d list into a 2d dictionary. I haven't worked much with 2d dictionaries prior to this so please bear with me. I am just wondering why this keeps pulling up a KeyError. In this quick example I would want the dictionary to look like {gender: { name: [food, color, number] }}
2dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = {}
for i in range(len(2dList)):
dict[2dList[i][0]][2dList[i][1]] = [2dList[i][2], 2dList[i][3], 2dList[i][4]]
I keep getting the error message: KeyError: 'male'. I know this is how you add keys for a 1d dictionary, but am unsure regarding 2d dictionaries. I always believed it was:
dictionary_name[key1][key2] = value
You can try this :) It will also work if you have more than one male or female in your List
List = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
d = {}
for l in List:
gender = l[0]
name = l[1]
food = l[2]
color = l[3]
number = l[4]
if gender in d: # if it exists just add new name by creating new key for name
d[gender][name] = [food,color,number]
else: # create new key for gender (male/female)
d[gender] = {name:[food,color,number]}
You are attempting to build a nested dictionary. But are not explicitly initializing the second-layer dictionaries. You need to do this each time, a new key is encountered. Btw, 2dlist is an erroneous way to declare variables in python. This should work for you:
dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = {}
for i in range(len(dList)):
if not dList[i][0] in dict.keys():
dict[dList[i][0]] = {}
dict[dList[i][0]][dList[i][1]] = [dList[i][2], dList[i][3], dList[i][4]]
print(dict)
To get more or less "sane" result use the following (list of dictionaries, each dict is in format {gender: { name: [food, color, number] }}):
l = [['male','josh','chicken','purple','10'], ['female','Jenny','steak','blue','11']]
result = [{i[0]: {i[1]:i[2:]}} for i in l]
print(result)
The output:
[{'male': {'josh': ['chicken', 'purple', '10']}}, {'female': {'Jenny': ['steak', 'blue', '11']}}]
You are getting a KeyError because you are trying to access a non-existing entry on the dictionary with male as the key
You can use defaultdict instead of dict.
from collections import defaultdict
2dList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dict = defaultdict(list)
for i in range(len(2dList)):
dict[2dList[i][0]][2dList[i][1]] = [2dList[i][2], 2dList[i][3], 2dList[i][4]]
Try this
twodList = [['male','josh','chicken','purple','10'],
['female','Jenny','steak','blue','11']]
dic = {twodList[i][0]: {twodList[i][1]: twodList[i][2:]} for i in range(len(twodList))}
As someone mentioned in the comments, you cannot have a variable starting with a number.
list1=[['male','josh','chicken','purple','10'],['female','Jenny','steak','blue','11'],['male','johnson','chicken','purple','10'],['female','jenniffer','steak','blue','11']]
dict = {}
for i in range(len(list1)):
if list1[i][0] in dict:
if list1[i][1] in dict[list1[i][0]]:
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]][list1[i][1]] = {}
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]] = {}
if list1[i][1] in dict[list1[i][0]]:
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
else:
dict[list1[i][0]][list1[i][1]] = {}
dict[list1[i][0]][list1[i][1]] = [list1[i][2], list1[i][3], list1[i][4]]
print dict
Above one gives below output:
{"male":{"josh":["chicken","purple","10"],"johnson":["chicken","purple","10"]},"female":{"jenniffer":["steak","blue","11"],"Jenny":["steak","blue","11"]}}
I've a list with master keys and a list of list of lists, where the first value of each enclosed list (like 'key_01') shall be a sub key for the corresponding values (like 'val_01', 'val_02'). The data is shown here:
master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]
I would like these lists to be combined into a dictionary of dictionaries, like this:
master_dic = {
"Master_01": {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
"Master_02": {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
"Master_03": {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}
What I've got so far is the sub dict:
import itertools
master_dic = {}
servant_dic = {}
keys = []
values = []
for line in data_long:
for item in line:
keys.extend(item[:1])
values.append(item[1:])
servant_dic = dict(itertools.izip(keys, values))
Which puts out a dictionary, as expected.
servant_dic = {
'key_06': ['val_11','val_12'], 'key_04': ['val_08','val_07'], 'key_05': ['val_09','val_10'],
'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06'], 'key_01': ['val_01','val_02']
}
The problem is, that if I want to add the master_keys to this dictionary, so I get the wanted result, I'd have to do this in a certain order, which would be possible, if each line had a counter like this:
enumerated_dic =
{
0: {'key_01':['val_01','val_02'],'key_02': ['val_03','val_04'], 'key_03': ['val_05','val_06']},
1: {'key_04': ['val_07','val_08'], 'key_05': ['val_09','val_10'], 'key_06': ['val_11','val_12']},
2: {'key_07': ['val_13','val_14'], ['key_08': ['val_15','val_16'], 'key_09': ['val_17','val_18']}
}
I'd love to do this with enumerate(), while each line of the servant_dic is build, but can't figure out how. Since afterwards, i could simply replace the counters 0, 1, 2 etc. with the master_keys.
Thanks for your help.
master_keys = ["Master_01", "Master_02", "Master_03"]
data_long = [[['key_01','val_01','val_02'],['key_02','val_03','val_04'], ['key_03','val_05','val_06']],
[['key_04','val_07','val_08'], ['key_05','val_09','val_10'], ['key_06','val_11','val_12']],
[['key_07','val_13','val_14'], ['key_08','val_15','val_16'], ['key_09','val_17','val_18']]]
_dict = {}
for master_key, item in zip(master_keys, data_long):
_dict[master_key] = {x[0]: x[1:] for x in item}
print _dict
Hope this will help:
{master_key: {i[0]: i[1:] for i in subkeys} for master_key, subkeys in zip(master_keys, data_long)}
My functional approach:
master_dic = dict(zip(master_keys, [{k[0]: k[1::] for k in emb_list} for emb_list in data_long]))
print(master_dic)
You can also use pop and a dict comprehension:
for key, elements in zip(master_keys, data_long):
print {key: {el.pop(0): el for el in elements}}
...:
{'Master_01': {'key_02': ['val_03', 'val_04'], 'key_03': ['val_05', 'val_06']}}
{'Master_02': {'key_06': ['val_11', 'val_12'], 'key_04': ['val_07', 'val_08'], 'key_05': ['val_09', 'val_10']}}
{'Master_03': {'key_07': ['val_13', 'val_14'], 'key_08': ['val_15', 'val_16'], 'key_09': ['val_17', 'val_18']}}
I want to create a few dictionaries: Dict1, Dict2, Dict3, ..., Dict15 within a for-loop.
dictstr = 'dict'
for ii in range(1,16):
dictstrtemp = dictstr
b = str(ii)
dictstrtemp += b #--> "dictii" created; where ii is 1, 2, ..., 15
print(dictstrtemp)
The output are 15 strings, from "dict1" to "dict15".
Now I want to assign each "dictii" some entries and reference them each outside of the for-loop. How do I do that? If I add "dictstrtemp = {}", then I can't reference it as "dict4" (for exapmle), it is only dictstrtemp. But I want to be able to enter "dict4" in the console and get the entries of dict4.
dictstr = 'dict'
dictlist = []
for ii in range(16):
dictstrtemp = dictstr
b = str(ii)
dictstrtemp += b #--> "dictii" created; where ii is 1, 2, ..., 15
dictlist.append(dictstrtemp)
print(dictstrtemp)
print(dictlist[4])
'dict4'
Or with list comprehension:
dictstr = 'dict'
dictlist = [dictstr + str(i) for i in range(16)]
Try this. Here I stored the dictionaries in another dict, using the indes as a number... you can use something else.
dict_of_dicts = {}
for ii in range(16):
my_dict = {'dict' + str(ii) : 'whatever'}
dict_of_dicts[ii] = my_dict
# now here, access your dicts
print dict_of_dicts[4]
# will print {'dict4' : whatever}