Unpack index, key, and value when enumerating over dictionary items - python

Let's say I have the following code:
my_dict = {str(n*100): n for n in range(5)}
for index, key_value in enumerate(my_dict.items()):
print(index, key_value[0], key_value[1])
Which would create a dictionary with 5 keys and then print (index, key, value) for each key-value pair in the dictionary.
Is there a more elegant way to unpack the dictionary items so that I could do something like:
for index, key, value in unpack_index_and_items(my_dict):
print(index, key, value)
Preferably I'm looking for a one-line replacement for the unpack_index_and_items placeholder and not an actual function.

You are almost there. Just use this:
for index, (k, val) in enumerate(my_dict.items()):
print(index, k, val)
Note the parenthesis around k, val. Without it you get ValueError: need more than 2 values to unpack. The reason is items() returns a (key, value) pair. Look here. Without parenthesis, the tuple returned by items() gets assigned to k, and there is nothing to assign to val, which is why you get the error need more than 2 values to unpack. However, with the parenthesis, the tuple returned by items() is assigned to the tuple (k, val).
I renamed the variables to k and val to distinguish between (key, value) pair returned by items() and the variable names in this example.
Edit: Read about tuple assignment here. Also PEP 3132: Extended Iterable Unpacking

Sure, you can do this:
for index, (key, value) in enumerate(my_dict.items()):
print index, key, value

Related

Comparing the strings in key and value of the same dictionary

I am looking to solve a problem to compare the string of the key and value of the same dictionary.
To return a dictionary of all key and values where the value contains the key name as a substring.
a = {"ant":"antler", "bi":"bicycle", "cat":"animal"}
the code needs to return the result:
b = {"ant":"antler", "bi":"bi cycle"}
You can iterate through the dictionary and unpack the key and the value at the same time this way:
b = {}
for key, value in a.items():
if value in key:
b[value] = key
This will generate your wanted solution. It does that by unpacking both the key and the value and checking if they match afterward.
You can also shorten that code by using a dictionary comprehension:
b = {key:value for key, value in a.items() if key in value}
This short line does the exact same thing as the code before. It even uses the same functionalities with only one addition - a dictionary comprehension. That allows you to put all that code in one simple line and declare the dictionary on the go.
answer = {k:v for k,v in a.items() if k in v}
Notes:
to iterate over key: value pair we use dict.items();
to check if a string is inside some other string we use in operator;
to filter items we use if-clause in the dictionary comprehension.
See also:
about dictionary comprehensions
about operators in and not in

how to extract a specific key value pair from a dict with a nested list of dicts

I have the following data structure whereby I would like to extract a given key: value pair by searching for the specific value. Use Case: I need to extract u'LOB_B': u'mcsmsg.example.net' from the dict.
{u'status': u'successful',
u'availableFqdnList': [
{u'LOB_A': u'pcload.us.example.net'},
{u'LOB_B': u'mcsmsg.example.net'},
{u'LOB_B': u'gtxd.example.net'},
{u'LOB_B': u'diamond.example.net'}]}
for key, value in my_dict.values():
if value == 'mcsmsg.example.net':
print("Print key value pairs for available FQDN list")
print key, "=", value
Error = for key, value in my_dict.values():
ValueError: too many values to unpack
I don't think values() is the function you want.
Probably you want items() instead.
If you are using python2, you can using iteritems()
Or for python3, it's items()
They will iter the key, value in the dictionary for you.
dic = {'a':1,'b':2}
for key,value in dic.items():
print(key)
print(value)
it will return
a
1
b
2
As a simple to understand way of getting this done
d = {u'status': u'successful',
u'availableFqdnList': [{u'LOB_A': u'pcload.us.example.net'},
{u'LOB_B': u'mcsmsg.example.net'},
{u'LOB_B': u'gtxd.example.net'},
{u'LOB_B': u'diamond.example.net'}]}
for val in d['availableFqdnList']:
if val.values()[0] == "mcsmsg.example.net":
print("%s=%s" %(val.keys()[0], val.values()[0]))

Lua's "Generic For Loop" for Python?

So, I've been searching endlessly for something similiar to Lua's "Generic For Loop" in Python.
I've been working on a simple text based game in Python, and I've been working with dictionaries a lot.
Here is something I'm looking for (in Lua):
Dictionary = {
"Red" = "There is some red paint on the walls.",
"Green" = "There is a little bit of green paint on the floor.",
}
for i, v in pairs(Dictionary) do
print(i, v)
end
What this will do is, go through the dictionary, then print out the INDEX and the VALUE. How would I do something like this in Python?
I know there is this:
for i in Dictionary:
print(i)
But that just prints the INDEX. I would like to access both the INDEX and the VALUE. Something like:
for i, v in Dictionary:
print(i, v)
Any help is appreciated.
You're looking for items. Iterating over a dict just gives you the keys, so you'd have to do:
for key in my_dict:
x = my_dict[key]
What you want is this:
for key, value in my_dict.items():
# do something
two ways:
for i, v in Dictionary.items():
print(i, v) #outputs pairs as key value
for tup in Dictionary.items(): #same thing
print(tup) # outputs pairs as (key,value)
or
for key in Dictionary:
print(key,Dictionary[key])
EDIT RESPONSE TO COMMENT:
>>> d = {1:1,2:2,3:3,4:4}
>>> for item in d.items(): print(item)
(1, 1)
(2, 2)
(3, 3)
(4, 4)
>>> for key,val in d.items(): print(key,val)
1 1
2 2
3 3
4 4
this is because in the first loop, item is a tuple and the __repr__ for a tuple has the brackets and commas as part of it where as the second loop splits the tuple into two seperate variables. print then automatically adds a space delimiter in between each parameter passed in the print function.
As explained by Two-Bit Alchemist:
In case it's not entirely clear still, in the tup formulation you'd access the key and value as tup[0] and tup[1], respectively. for key, val in my_dict.items(): ... and for tup in my_dict.items(): key, val = tup is the same setup. The point is you can use tuple unpacking just fine inline in a for loop.
The items method (or in Py2, viewitems or iteritems to avoid making a whole new list containing copies of the dict key/value pairs) is the way to go:
for k, v in Dictionary.items(): # For performance, use .viewitems() on Py2.7, .items() on Py3.x
print(k, v)

Dictionary Iterating -- for dict vs for dict.items()

When we iterate over the dictionary below, each iteration returns(correctly) a key,value pair
for key, value in dict.items():
print "%s key has the value %s" % (key, value)
'some key' key has the value 'some value' (repeated however many times there are a k,v pair)
The above makes sense to me, however if we do this:
for key in dict.items():
print "%s key has the value %s" % (key, value)
("some key", "some value") has the value "some value" (the left tuple will iterate through each key value pair and the right value will just stay at the first value in the dict and repeat)
We end up getting each k,v pair returned in the first %s (key) and the 2nd %s (value) does not iterate, it just returns the first value in the dict for each iteration of the for loop.
I understand that if you iterate with only for key in dict then you are iterating over the keys only. Here since we are iterating a set of tuples (by using dict.items()) with only the key in the for loop, the loop should run for the same number of times as the first example, since there are as many keys as key,value pairs.
What I'm having trouble grasping is why python gives you the entire tuple in the second example for key.
Thanks for the help all -- I'd like to add one more question to the mix.
for a,a in dict.items():
print a
Why does the above print the value, and if i print a,a - obviously both values are printed twice. If I had typed for a,b I would be iterating (key,value) pairs so I would logically think I am now iterating over (key,key) pairs and would therefore print key rather than value. Sorry for the basic questions just playing around in interpreter and trying to figure stuff out.
The first example is utilizing something known as "tuple unpacking" to break what is REALLY the same tuple as in your separate example down into two different variables.
In other words this:
for key, value in dict.items():
Is just this:
for keyvalue in dict.items():
key, value = keyvalue[0], keyvalue[1]
Remember that a for loop always iterates over the individual elements of the iterator you give it. dict.items() returns a list-like object of tuples, so every run through the for loop is a new tuple, automatically unpacked into key, value if you define it as such in the for loop.
It may help to think of it this way:
d = {'a':1, 'b':2, 'c':3}
list(d) # ['a', 'b', 'c'] the keys
list(d.keys()) # ['a', 'b', 'c'] the keys
list(d.values()) # [1, 2, 3] the values
list(d.items()) # [('a',1), ('b',2), ('c',3)] a tuple of (key, value)
N.B. that the only reason your code
for key in dict.items():
print "%s key has value: %s" % (key, value)
Does not throw a NameError is because value is already defined from elsewhere in your code. Since you do not define value anywhere in that for loop, it would otherwise throw an exception.
In the second example you gave you are not assigning "value" to anything:
Notice the small edit here:
for key in dict: ##Removed call to items() because we just want the key,
##Not the key, value pair
value = dict[key] # Added this line
print "%s key has the value %s (key, value)
Note:
In the second example, you could now call dict.keys() or just dict (referencing a dictionary in a for loop will return it's keys). Calling dict.items() will confusingly assign
key=(, )
which is probably not what you want.

can we access key and value in the ordereddict in python.?

I worked to access the item in ordered dictionary. d is the ordered dictionary:
print d.items()
Here the output is a pair. I want to access the key and value in this pair.
You can unpack the key, value (a tuple) as below:
for key, value in d.items():
print (key)
print (value)
This works both on python 2 and 3.
From docs:
Return a new view of the dictionary’s items ((key, value)
pairs).
Each "pair" in d.items() is a tuple (ordered, immutable sequence) (key, value). You can "unpack" the values in each tuple into separate names, for example in a for loop:
for key, value in d.items():

Categories

Resources