Question 1.)
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.
Question 2.)
for key,value in dict.items():
print "%s is the key that corresponds to the value %s"%(key,value)
The above example makes sense to me, but why does:
for key in dict.items():
print "%s is the key that corresponds to the value %s"%(key)
produce the same result? Is it because even though we aren't unpacking the tuple into two separate variables in the for statement, it is returned as (key,value) in the string formatter through the key call - basically making %(key) = (key,value)?
Q1:
Consider the following:
>>> d = {"a": 1, "b": 2, "c": 3}
>>> xs = d.items()
>>> a, a = xs[0]
>>> print a, a
1 1
This is effectively what is happening. You are unpacking each (key, value) pair into (a, a) effectively ending up with (value, value). The reference to the key is lost.
This is the same as:
>>> a, a = 1, 2
>>> print a, a
2, 2
What happens here in the interpreter during the unpacking:
a becomes 1.
a becomes 2.
Q2:
Consider the following:
>>> a, b = ("a", 1)
>>> print "%s=%s" % (a, b)
a, 1
>>> x = ("a", 1)
>>> print "%s=%s" % x
a, 1
The two are effectively the same. Since your string interpolation is expecting a tuple of two both (a, b) and x (a tuple of 2 values) effectively satisfies this.
You right. key is now tuple (k,v) and "..."% expect tuple with arguments. And ((k,v)) ( in ".." % ((k,v)) ) doesn't give "tuple in tuple" but only "single-level" tuple - like (1) doesn't give tuple but integer 1 - so you have "..." % (k,v)
d={1:2,4:5,6:7,8:8}
for a,a in d.items():
print(a,a)
In dictionary ,
a,a runs with (key,value)
And ends up with (value,value)
Output:
Starts with (1,2) ends with (2,2)
Starts with (4,5) ends with (5,5)
Starts with (6,7) ends with (7,7)
Starts with (8,8) ends with (8,8)
So Actual Output:
2 2
5 5
7 7
8 8
Related
I saw this Python snippet on Twitter and was quite confused by the output:
>>> a, b = a[b] = {}, 5
>>> a
{5: ({...}, 5)}
What is going on here?
From the Assignment statements documentation:
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
You have two assignment target lists; a, b, and a[b], the value {}, 5 is assigned to those two targets from left to right.
First the {}, 5 tuple is unpacked to a, b. You now have a = {} and b = 5. Note that {} is mutable.
Next you assign the same dictionary and integer to a[b], where a evaluates to the dictionary, and b evaluates to 5, so you are setting the key 5 in the dictionary to the tuple ({}, 5) creating a circular reference. The {...} thus refers to the same object that a is already referencing.
Because assignment takes place from left to right, you can break this down to:
a, b = {}, 5
a[b] = a, b
so a[b][0] is the same object as a:
>>> a, b = {}, 5
>>> a[b] = a, b
>>> a
{5: ({...}, 5)}
>>> a[b][0] is a
True
I have a few variables in python3:
a = 1
b = [2,3,4]
c = 5
I want to get a tuple which is from above variables, like: (1,2,3,4,5)
what is the easiest way to do that in python3?
Creating a tuple in Python is as simple as putting the stuff you need in a tuple in parentheses:
my_tuple = (1, 2, 3)
a = 1
b = 2
c = 3
another_tuple = (a, b, c) # also works with variables, or anything else with a value
And if what you want in the tuple is in something else that can be unpacked, like a list or a tuple itself, you can use the unpacking operator * to unpack it into the new tuple:
a = 1
b = [2,3,4]
c = 5
my_tuple = (a, *b, c)
Not your question, but note that you can also get stuff from a tuple without using the * operator, as it's implied in an assignment statement:
x, _, z = my_tuple # continued from before
In this example, what was in a (1) is now also in x and what was in c also in z. What was in b and in the second position of the tuple gets discards (that's what the underscore _ here means, "don't care".)
You use the unpack operator in cases where you explicitly need to unpack and you're constructing some new variable, or need the elements of the tuple separately where they could also be used as a tuple. For example, when calling a function:
a_tuple = ('Hi there', 'John')
def greeting(phrase='Hello', name='world'):
print(f'{phrase}, {name}!')
greeting(*a_tuple)
In this example, calling greeting as greeting(a_tuple) would give you the very nasty result of ('Hi there', 'John'), world!, clearly not what you want, but you can still use the tuple with the unpack operator.
And the other obvious example is one like the one solving OP's question.
Simply create a new tuple as shown below.
newTuple=(a, *b, c)
Note: *b unpacks list b into variables and add each variable to indexes of newTuple
One of the ways is shown below
from functools import reduce
import operator
# create a bunch of lists, reduce them to one list and finally convert to tuple
result = tuple(reduce(operator.add, ([a], b, [c])))
print(result)
This is the most pythonic solution:
a = 1
b = [2,3,4]
c = 5
res = a,*b,c
# output: (1,2,3,4,5)
Note: To create the new tuple, round brackets are not necessary in Python3
I am new to python and was trying to make a dict of pairs in python.
What I would have done in c++ is
dist[make_pair(a,b)]=1
I am not sure how I can do the same in python
Edit
What I basically want to do is to map a pair of two integers to some value-
for example-
(1,2) -> 1
(1,3) -> 2
(2,1) ->3
I want to map pairs to some integer value
You can use the data structure "tuple" as a key in the dictionary. If you want to define a function that returns a n-tuple given n inputs, you can do that also.
a = 4
b = 5
dict_example = dict()
dict_example[(a,b)] = 1
print dict_example[(a,b)]
This prints the value of key (a,b), which is 1
To create an element having the tuple (a,b) as key, and 1 as a value, you just have to do :
new_dict = {(a,b) : 1}
If such a dict already exist, and you want to add the pair a,b as a key and 1 as a value, you have to do :
existing_dict[(a,b)] = 1
You can also use existing_dict[a,b] = 1 as Duncan pointed out.
I guess you tried using an array as a dict key, like:
>>> d = {}
>>> pair = [0, 1]
>>> d[pair] = 'foo'
TypeError: unhashable type: 'list'
Ok, what is that? Python dict keys must not be mutable. They can be numbers, strings and other hashable types - you can't use mutable types like lists, dicts and other mutable collections.
There is a collection that is very like a list but is not mutable: the tuple.
>>> d[tuple(pair)] = 'foo'
>>> d
{(1, 2): 'foo'}
As you can see, the literal for a tuple is (v1, v2, ..., vN). In places where it is not ambiguous, you can even omit the parenthesis:
>>> pair = 0, 1
>>> pair
(0, 1)
More than once I was bit by this when I left a trailing comma while refactoring code:
>>> x = 1, # I meant x = 1
>>> x
(1,)
That is the literal for a tuple with just 1 element.
This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 8 months ago.
Reading through Peter Norvig's Solving Every Sudoku Puzzle essay, I've encountered a few Python idioms that I've never seen before.
I'm aware that a function can return a tuple/list of values, in which case you can assign multiple variables to the results, such as
def f():
return 1,2
a, b = f()
But what is the meaning of each of the following?
d2, = values[s] ## values[s] is a string and at this point len(values[s]) is 1
If len(values[s]) == 1, then how is this statement different than d2 = values[s]?
Another question about using an underscore in the assignment here:
_,s = min((len(values[s]), s) for s in squares if len(values[s]) > 1)
Does the underscore have the effect of basically discarding the first value returned in the list?
d2, = values[s] is just like a,b=f(), except for unpacking 1 element tuples.
>>> T=(1,)
>>> a=T
>>> a
(1,)
>>> b,=T
>>> b
1
>>>
a is tuple, b is an integer.
_ is like any other variable name but usually it means "I don't care about this variable".
The second question: it is "value unpacking". When a function returns a tuple, you can unpack its elements.
>>> x=("v1", "v2")
>>> a,b = x
>>> print a,b
v1 v2
The _ in the Python shell also refers to the value of the last operation. Hence
>>> 1
1
>>> _
1
The commas refer to tuple unpacking. What happens is that the return value is a tuple, and so it is unpacked into the variables separated by commas, in the order of the tuple's elements.
You can use the trailing comma in a tuple like this:
>>> (2,)*2
(2, 2)
>>> (2)*2
4
I saw this Python snippet on Twitter and was quite confused by the output:
>>> a, b = a[b] = {}, 5
>>> a
{5: ({...}, 5)}
What is going on here?
From the Assignment statements documentation:
An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.
You have two assignment target lists; a, b, and a[b], the value {}, 5 is assigned to those two targets from left to right.
First the {}, 5 tuple is unpacked to a, b. You now have a = {} and b = 5. Note that {} is mutable.
Next you assign the same dictionary and integer to a[b], where a evaluates to the dictionary, and b evaluates to 5, so you are setting the key 5 in the dictionary to the tuple ({}, 5) creating a circular reference. The {...} thus refers to the same object that a is already referencing.
Because assignment takes place from left to right, you can break this down to:
a, b = {}, 5
a[b] = a, b
so a[b][0] is the same object as a:
>>> a, b = {}, 5
>>> a[b] = a, b
>>> a
{5: ({...}, 5)}
>>> a[b][0] is a
True