-1

I have a dictionary

Example: dict = {'one':1 ,'two':2 , 'three':3}

I want to use/have two values within single iteration of for loop. End result should be like this

# 1 2 (First iteration)
# 1 3 (Second iteration) 
# 2 1
# 2 3 
# 3 1 
# 3 2 

Can someone please tell how I can achieve this in python dictionary.

for i in dict.values():

  # how do i Access two values in single iteration and to have result like mentioned       above

Thanks

Thomsan
  • 11
  • 3

3 Answers3

1
import itertools
d = {'one':1 ,'two':2 , 'three':3}
l = list(itertools.permutations(d.values(),2))

>>> l
[(3, 2),
 (3, 1),
 (2, 3),
 (2, 1),
 (1, 3),
 (1, 2)]

for x, y in l:
    # do stuff with x and y
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

You can get the desired output order by ordering the permutations of the dicts values, eg:

from itertools import permutations

dct = {'one':1 ,'two':2 , 'three':3}
for fst, snd in sorted(permutations(dct.itervalues(), 2)):
    print fst, snd # or whatever
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
-1

Actually i want to access the values only so i am using this function dict.values() Example it should be like this x = 1 , y =2 these values will be used as an arguments to another function self.funct(x,y)

In your comment it seemed like you just wanted both numbers for another function. If you don't mind nested loops, this should suffice:

d = {'one':1 ,'two':2 , 'three':3}
dvals = sorted(d.values()

for x in dvals:
  for y in dvals:
    if x != y: 
      self.funct(x,y)
Tai
  • 490
  • 4
  • 18
  • The -1 is for not answering the "having two values in a single iteration," part of the question correct? It seemed to me from his comment that Thomsan amended his goal. If there is another reason for the minus- i.e. a better way of doing it other than the loop or itertools, please let me know. – Tai Sep 29 '14 at 16:44