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
Related
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
I build a dictionary (d) that looks as such:
d = {'compartment 1': ['500002', '500012', '305667'],
'compartment2': ['500002', '500012', '305667', '500010', '500038', '311984'],
'complex': ['310698', '500072', '308090']}
I also build a set of unique elements that correspond to keys of the dict (e.g.'500002') and I know for sure that each element of the set matches a value in dictionary at least once, but possible it has two, three, ... corresponding keys.
What I now want is to print out for each unique element in the set all it's corresponding values on one line.
this is what I came up with:
for u in uniqueset:
for x, y in d.iteritems():
for number in y:
if y == u:
print u, x
The result is that it prints every unique item multiple times on different lines. I want it to print it just once on one line, followed by all the keys that correspond. I thought I could do it with a nested for loop, but maybe that's not the way to go about it.
How could I do this? -- Hope I'm clear..
Thank you.
You can use a list comprehension like so
>>> [key for key in d if '500002' in d[key]]
['compartment 1', 'compartment2']
If you have a set, and you want to find each key that has each item (if I understood your question), you could do this
s = set(['308090', '500012', '500072', '305667', '311984', '500010', '500002', '500038', '310698'])
for item in s:
print item, [key for key in d if item in d[key]]
Output
308090 ['complex']
310698 ['complex']
311984 ['compartment2']
500038 ['compartment2']
500072 ['complex']
305667 ['compartment 1', 'compartment2']
500012 ['compartment 1', 'compartment2']
500010 ['compartment2']
500002 ['compartment 1', 'compartment2']
It you're more comfortable using for loops, you can do something like this
for item in s:
keyList = []
for key in d:
if item in d[key]:
keyList.append(key)
print item, keyList
I want pop out all the large values and its keys in a dictionary, and keep the smallest. Here is the part of my program
for key,value in dictionary.items():
for key1, value1 in dictionary.items():
if key1!= key and value > value1:
dictionary.pop(key)
print (dictionary)
Which results in
RuntimeError: dictionary changed size during iteration
How can I avoid this error?
In Python3, Try
for key in list(dict.keys()):
if condition:
matched
del dict[key]
1 more thing should be careful when looping a dict to update its key:
Code1:
keyPrefix = ‘keyA’
for key, value in Dict.items():
newkey = ‘/’.join([keyPrefix, key])
Dict[newkey] = Dict.pop(key)
Code2:
keyPrefix = ‘keyA’
for key, value in Dict.keys():
newkey = ‘/’.join([keyPrefix, key])
Dict[newkey] = Dict.pop(key)
Result of code1/code2 is:
{‘keyA/keyA/keyB’ : ”, ‘keyA/keyA/keyA’: ”}
My way to resolve this unexpected result:
Dict = {‘/’.join([keyPrefix, key]): value for key, value in Dict.items()}
Link: https://blog.gainskills.top/2016/07/21/loop-a-dict-to-update-key/
Alternative solutions
If you're looking for the smallest value in the dictionary you can do this:
min(dictionary.values())
If you cannot use min, you can use sorted:
sorted(dictionary.values())[0]
Why do I get this error?
On a side note, the reason you're experiencing an Runtime Error is that in the inner loop you modify the iterator your outer loop is based upon. When you pop an entry that is yet to be reached by the outer loop and the outer iterator reaches it, it tries to access a removed element, thus causing the error.
If you try to execute your code on Python 2.7 (instead of 3.x) you'll get, in fact, a Key Error.
What can I do to avoid the error?
If you want to modify an iterable inside a loop based on its iterator you should use a deep copy of it.
You can use copy.deepcopy to make a copy of the original dict, loop over the copy while change the original one.
from copy import deepcopy
d=dict()
for i in range(5):
d[i]=str(i)
k=deepcopy(d)
d[2]="22"
print(k[2])
#The result will be 2.
Your problem is iterate over something that you are changing.
Record the key during the loop and then do dictionary.pop(key) when loop is done. Like this:
for key,value in dictionary.items():
for key1, value1 in dictionary.items():
if key1!= key and value > value1:
storedvalue = key
dictionary.pop(key)
Here is one way to solve it:
From the dictionary, get a list of keys, sorted by value
Since the first key in this list has the smallest value, you can do what you want with it.
Here is a sample:
# A list of grades, not in any order
grades = dict(John=95,Amanda=89,Jake=91,Betty=97)
# students is a list of students, sorted from lowest to highest grade
students = sorted(grades, key=lambda k: grades[k])
print 'Grades from lowest to highest:'
for student in students:
print '{0} {1}'.format(grades[student], student)
lowest_student = students[0]
highest_student = students[-1]
print 'Lowest grade of {0} belongs to {1}'.format(grades[lowest_student], lowest_student)
print 'Highest grade of {0} belongs to {1}'.format(grades[highest_student], highest_student)
The secret sauce here is in the sorted() function: instead of sorting by keys, we sorted by values.
If you want to just keep the key with the smallest value, I would do it by first finding that item and then creating a new dictionary containing only it. If your dictionary was d, something like this would do that in one line:
d = dict((min(d.items(), key=lambda item: item[1]),))
This will not only avoid any issues about updating the dictionary while iterating it, it is probably faster than removing all the other elements.
If you must do the modifications in-place for some reason, the following would work because it makes a copy of all the keys before modifying the dictionary:
key_to_keep = min(d.items(), key=lambda item: item[1])[0]
for key in list(d):
if key != key_to_keep:
d.pop(key)
As I read your loop right now, you're looking to keep only the single smallest element, but without using min. So do the opposite of what your code does now, check if value1 < minValueSoFar, if so, keep key1 as minKeySoFar. Then at the end of the loop (as Zayatzz suggested), do a dictionary.pop(minKeySoFar)
As an aside, I note that the key1!=key test is irrelevant and computationally inefficient assuming a reasonably long list.
minValueSoFar = 9999999; # or whatever
for key,value in dictionary.items():
if value < minValueSoFar:
minValueSoFar = value
minKeySoFar = key
dictionary.pop(minKeySoFar) # or whatever else you want to do with the result
An alternative solution to dictionary changed size during iteration:
for key,value in list(dictionary.items()):
for key1, value1 in list(dictionary.items()):
if key1!= key and value > value1:
dictionary.pop(key)
print (dictionary)
Better use it with caution! when using this type of code, because list(dictionary.items()) calculated when the complier enters first time to loop. Therefore any change made on dictionary won't affect process inside the current loop.
You could create a list with the vaules you want to delete and than run a second for loop:
for entry in (listofkeystopop):
dictionary.pop(entry)
I wrote the below code working with dictionary and list:
d = computeRanks() # dictionary of id : interestRank pairs
lst = list(d) # tuples (id, interestRank)
interestingIds = []
for i in range(20): # choice randomly 20 highly ranked ids
choice = randomWeightedChoice(d.values()) # returns random index from list
interestingIds.append(lst[choice][0])
There seems to be possible error because I'm not sure if there is a correspondence between indices in lst and d.values().
Do you know how to write this better?
One of the policies of dict is that the results of dict.keys() and dict.values() will correspond so long as the contents of the dictionary are not modified.
As #Ignacio says, the index choice does correspond to the intended element of lst, so your code's logic is correct. But your code should be much simpler: d already contains IDs for the elements, so rewrite randomWeightedChoice to take a dictionary and return an ID.
Perhaps it will help you to know that you can iterate over a dictionary's key-value pairs with d.items():
for k, v in d.items():
etc.
I am really new to python and I can't find any information about this. I have an associative array item,
item['id'] = 0
item['title'] = 'python'
I want to validate the contents of item but I dont want to use the index name like 'title' but just have a for loop and iterate over all entries in item regardless of their meaning. Something like that
for a in range(0, len(item)):
print (item[a])
Any ideas or suggestions?
In Python, associative arrays are called dictionaries.
A good way to iterate through a dict is to use .iteritems():
for key, value in item.iteritems():
print key, value
If you only need the values, use .itervalues():
for value in item.itervalues():
print value
As you learn more about Python and dictionaries, take note of the difference between .iteritems()/itervalues() (which returns an iterator) and items()/values()(which returns a list (array)).
In Python 3
.iteritems()/.itervalues() have been removed and items()/values()/keys() return iterators on the corresponding sequences.
for key, value in item.items():
print(key)
print(value)
There are three ways to iterate a dictionary:
item = {...}
for key in item: # alternatively item.iterkeys(), or item.keys() in python 3
print key, item[key]
item = {...}
for value in item.itervalues(): # or item.values() in python 3
print value
item = {...}
for key, value in item.iteritems(): # or item.items() in python 3
print key, value