I'm trying to traverse through a dictionary that essentially contains tuples and keys for tuples like this:
(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
I need to access the value of the key, i.e., the string of the tuple. I tried many things, like converting to the dictionary, using key[0] just gives me "'int' object is not subscribable"..
def matching_score(k, tokens, tf_idf_score):
print("Matching Score")
query_weights = {}
for word in tokens:
for key, value in tf_idf_score.items():
**if key in word**:
try:
query_weights[key[0]] += tf_idf_score[key]
except:
query_weights[key[0]] = tf_idf_score[key]
query_weights = sorted(query_weights.items(), key=lambda x: x[1], reverse=True)
print("")
l = []
for i in query_weights[:10]:
l.append(i[0])
print(l)
First, this is a recreation of your data as a dictionary:
d1 = {(101940039, 'yoel'): 0.0016034940264139383,
(101940039, 'yossi'): 0.004810482079241815,
(101940039, 'youngmen'): 0.0016034940264139383}
With keys() it is possible to access the keys. At the same time, we want to convert them into a list.
list(d1.keys())
The result is a list of tuples.
[(101940039, 'yoel'), (101940039, 'yossi'), (101940039, 'youngmen')]
To access individual items in this nested list: first, use the index of the list to select the desired list, and second, use the index of the tuple to select the desired item within.
list(d1.keys())[0][1]
'yoel'
To get all the string elements of the key tuples:
for i in range(len(d1)):
print(list(d1.keys())[i][1])
yoel
yossi
youngmen
Related
I have a dictionary where the values are a list of tuples.
dictionary = {1:[('hello, how are you'),('how is the weather'),('okay
then')], 2:[('is this okay'),('maybe It is')]}
I want to make the values a single string for each key. So I made a function which does the job, but I do not know how to get insert it back to the original dictionary.
my function:
def list_of_tuples_to_string(dictionary):
for tup in dictionary.values():
k = [''.join(i) for i in tup] #joining list of tuples to make a list of strings
l = [''.join(k)] #joining list of strings to make a string
for j in l:
ki = j.lower() #converting string to lower case
return ki
output i want:
dictionary = {1:'hello, how are you how is the weather okay then', 2:'is this okay maybe it is'}
You can simply overwrite the values for each key in the dictionary:
for key, value in dictionary.items():
dictionary[key] = ' '.join(value)
Note the space in the join statement, which joins each string in the list with a space.
It can be done even simpler than you think, just using comprehension dicts
>>> dictionary = {1:[('hello, how are you'),('how is the weather'),('okay then')],
2:[('is this okay'),('maybe It is')]}
>>> dictionary = {key:' '.join(val).lower() for key, val in dictionary.items()}
>>> print(dictionary)
{1: 'hello, how are you how is the weather okay then', 2: 'is this okay maybe It is'}
Now, let's go through the method
we loop through the keys and values in the dictionary with dict.items()
assign the key as itself together with the value as a string consisting of each element in the list.
The elemts are joined together with a single space and set to lowercase.
Try:
for i in dictionary.keys():
dictionary[i]=' '.join(updt_key.lower() for updt_key in dictionary[i])
The codes:
Cour_det = [("MA101","Calculus"),("PH101","Mechanics"),("HU101","English")];
Stu_det = [("UGM2018001","Rohit Grewal"),("UGP2018132","Neha Talwar")];
Grades = [("UGM2018001", "MA101", "AB"),("UGP2018132", "PH101", "B"),
("UGM2018001", "PH101", "B")];
Cour_det = sorted(Cour_det, key = lambda x : x[0]);
Stu_det = sorted(Stu_det, key = lambda x : x[0]);
Grades = sorted(Grades, key = lambda x : x[1]);
Grades = sorted(Grades, key =lambda x : x[0]);
B={}
#code by which i tried to add grade to nested list
for i in range(len(Stu_det)):
for j in range(len(Cour_det)):
B[Stu_det[i][0]][Cour_det[j][0]]=(Cour_det[j][1],Grades[][])
#here i am stuck on how to access grade of the course that i am adding
#it should look like this
B={"UGM2018001":{"MA101":("Calculus","AB'),"PH101":("Mechanics","B")}}
#above list for roll no UGM2018001,similarly other roll no.s as keys and
#course code can be keys of nested list for those roll no.s
In this code i want to make a nested dictionary in which the outer keys will be the roll no as what first element of every tuple of List Stu_det is(like UGM2018001) and then the nested keys will be the course code(like MA101) and then the element of each nested key will be a tuple or list which will have two elements, first element will be the course name(like Calculus) and second element i want the grade mentioned (like AB) but accessing the grade is becoming problem ,how to access it or to get its index. I am unable to get Grade of subject after making roll no. and course code key.
Here's a way of doing it using defaultdict module.
# load library
from collections import defaultdict
# convert to dictionary as this will help in mapping course names
Cour_det = dict(Cour_det)
Stu_det = dict(Stu_det)
# create a dictionary for grades
grades_dict = defaultdict(list)
for x in Grades:
grades_dict[x[0]].append(x[1:])
# create a new dict to save output
new_dict = defaultdict(dict)
# loop through previous dictionary and replace course codes with names
for k,v in grades_dict.items():
for val in v:
temp = list(val)
temp[0] = Cour_det[temp[0]]
new_dict[k].update({val[0]: tuple(temp)})
# print output
print(new_dict)
defaultdict(dict,
{'UGM2018001': {'MA101': ('Calculus', 'AB'),
'PH101': ('Mechanics', 'B')},
'UGP2018132': {'PH101': ('Mechanics', 'B')}})
I have a dictionary where the keys are integers and the values are strings. The dictionary has been sorted using key values.
I need to copy the corresponding string values (keeping the sorted order) to a list. I cannot figure out how to iterate over the dictionary.
I know the number of key-value pairs in the dictionary (let it be 'n').
Some_ordered_dict
resultant_list=[]
for i in range(n):
resultant_list.append(Some_ordered_dict[increment-key?]
The dictionary was sorted using OrderedDict from some dictionary 'dic' as follows;
od=collections.OrderedDict(sorted(dic.items()))
The essential point is that I have to display the strings values of the dictionary in the same order as they appear in the sorted dictionary.
resultant_list = [d[k] for k in sorted(d)]
The standard Python dictionary does not guarantee that items in a dictionary will be kept in any order. Next thing is that you have to iterate using a "for in" statement like such:
Some_ordered_dict
resultant_list=[]
for i in Some_ordered_dict:
resultant_list.append(Some_ordered_dict[i])
You should take a look at the ordered dict collection to ensure that the items on your dict are kept in the order that you expect.
Using the standard unordered dictionary in python you could use something like this:
resultant_list = []
for i in sorted(dict.keys()):
resultant_list.append(dict[i])
As mentioned in other posts, dictionaries do not guarantee order. One way to get a sorted list would be to created a list of tuples out of your dict's (key, value) pairs, then sort this list based n the first element(the key), as follows:
my_dict = {2: 'two', 3: 'three', 1: 'one'}
my_tuple_list = list(zip(my_dict.keys(), my_dict.values()))
my_sorted_list = sorted(my_tuple_list, key = lambda item: item[0])
resultant_list = [x[1] for x in my_sorted_list]
I'm trying to understand about dictionaries and list in Python.
Assume that I have a list which contains 3 dictionaries
Ex. item_list = [price,stock,quantity]
price, stock and quantity are the dictionaries here. Each dictionary has few key-value pairs like
price = {'toys':25,'clothes':[12,15,20]}
I know to access individual elements, I can use a for loop with the keys specified like:
for item in item_list:
print item['toys']
How do I access the elements without directly mentioning the key in the for loop?
You can iterate over a dictionary just like you can iterate over a list.
for item in item_list:
for key in item:
print item[key]
In a sense, you're still mentioning the keys, but you're not referencing them explicitly by their value.
If you're just interested in the values you can use the values() method:
for item in item_list:
for key in item.values():
print item[key]
My preferred way to iterate over dictionaries though is with items, which returns a tuple of key, value pairs.
for item in item_list:
for key, value in item.items():
print key, value
I would do something like this:
for item in item_list:
for key, value in item.iteritems():
print key, value
Let us say, you have a list like this
prices_list = [{'toys':25,'clothes':[12,15,20]},{'toys':35,'clothes':[12,15,20]}]
And you would like to get the value corresponding to toys, but without specifying the name in the for loop. So, you can use operator.itemgetter like this
from operator import itemgetter
getter = itemgetter("toys")
print [getter(item) for item in prices_list]
# [25, 35]
The same can be used like this
total = 0
for item in prices_list:
total += getter(item)
for d in item_list:
for i in d.values():
print i
You could also call d.items() and get back tuples of (key, value) if you wanted access to both.
Additionally if you don't care about readability you could use this to get a list of all the values accross the dicts in your list.
[x for y in (i.values() for i in item_list) for x in y]
You can also use: [d for i in item_list for d in i.values()] to get the values and flatten them into a list (though yours would still be nested because of clothes' value being a list.
Finally you can merge the dictionaries into one if they have distinct keys:
joint_mapping = dict([d for i in item_list for d in i.items()])
or if they don't have unique values you can use the below code to produce a dict of lists of values. :
for k, v in [d for i in item_list for d in i.items()]:
new_d[k] = new_d.get(k, [])+[v]
You mentioned :
#Eenvincible - I would be inputting those values to other variable.
Print is just an example I gave. So would not want to hardcode the key.
I think you can do your trick using for loop as mentioned in other answers.
for item in item_list:
for key in item:
print item[key]
tempvariable = item[key]
.... do something here.
If you want to assign each value to a seperate variable, you should:
- First, assign that variables to any insignificant value EX: **None** or *""*
- Then, dynamically use the for loop to reassign each variable to new value using if condition or thier index.
EX:
price_toys , price_clothes , stock_toys , stock_clothes = None , None , None , None
for item in item_list:
for key in item:
tempvariable = item[key]
# condition to choose which varible will be set to the current value.
if item == "price" and key == "toys":
price_toys = tempvariable
# and so on
I get this error message:
TypeError: list indices must be integers, not list
Using this code:
def invert_networks_dict(person_to_networks):
"""
(dict of {str: list of str}) -> dict of {str: list of str})
"""
networks_to_person = []
for person in person_to_networks:
networks = person_to_networks[person]
networks_to_person[networks] = person
if not (networks in networks_to_person):
networks_to_person[networks] = person
else:
networks_to_person[networks].append[person]
How can I fix it?
You should have initialized networks_to_person as dictionary:
networks_to_person = {}
networks_to_person = []
This assigns networks_to_person to a list. However, you want it to be a dict:
networks_to_person = dict() # <--
You can also use {} (empty dict literal), but I prefer dict() because it makes your intent more explicit.
#glglgl brought up a good point in the comments (which I'll restate here for completeness).
networks_to_person[networks].append[person]
You want to call append here, not index it. Therefore, you want:
networks_to_person[networks].append(person)
Lastly, note that you can't have lists as keys to a dictionary. You can convert them to tuples (which can be keys) instead using tuple().
if you want to 'reverse' dictionary d (swap keys and values), with values being list of strings you can:
dict((tuple(val), key) for key, val in d.items())
However, you can do this only if d.values are unique, as keys in new dictionary must be unique.
Explanation:
dict() is a built-in that creates dictionary from sequence of pairs (key, value). As with every dictionary, key must be hashable.
Because we want to make values of d new keys, we need to transform them to something hashable - in this case this will be tuple. We can create it from any sequence, including lists that are values of d, with another builtin: tuple().
So what we need are pairs of keys in values from d. We can get them using d.items(). We can make this in easy way using list comprehension, additionally wrapping val in tuple, to make it hashable, so it can be used as key:
[(tuple(val), key) for key, val in d.items())] # that would create list of pairs
But if we pass something to function, we don't need to create list, we can pass similar expression as generator comprehension, so our final code looks like:
result = dict((tuple(val), key) for key, val in d.items())
Do you know that a dict as a items function
So instead of that:
networks_to_person = {}
for person in person_to_networks:
networks = person_to_networks[person]
networks_to_person[networks] = person
You can do
networks_to_person = {}
for person, networks in person_to_networks.items():
networks_to_person[networks] = person
Which can also be written as:
networks_to_person = {networks: person for person, networks in person_to_networks.items()}