How to iterate over a dictionary of tuples

python iterate dictionary with tuple key
iterate through nested dictionary python
iterate list of dictionaries python
python add to dictionary in loop
how to use tuple as key in dictionary
python iterate dictionary key, value
while loop dictionary python
python iterate over dictionary values

I have a list of tuples called possible_moves containing possible moves on a board in my game:

[(2, 1), (2, 2), (2, 3), (3, 1), (4, 5), (5, 2), (5, 3), (6, 0), (6, 2), (7, 1)]

Then, I have a dictionary that assigns a value to each cell on the game board:

{(0,0): 10000, (0,1): -3000, (0,2): 1000, (0,3): 800, etc.}

I want to iterate over all possible moves and find the move with the highest value.

my_value = 0
possible_moves = dict(possible_moves)
for move, value in moves_values:
    if move in possible_moves and possible_moves[move] > my_value:
        my_move = possible_moves[move]
        my_value = value
return my_move

The problem is in the part for move, value, because it creates two integer indexes, but I want the index move to be a tuple.

IIUC, you don't even need the list of possible moves. The moves and their scores you care about are already contained in the dictionary.

>>> from operator import itemgetter
>>>
>>> scores = {(0,0): 10000, (0,1): -3000, (0,2): 1000, (0,3): 800}
>>> max_move, max_score = max(scores.items(), key=itemgetter(1))
>>>
>>> max_move
(0, 0)
>>> max_score
10000

edit: turns out I did not understand quite correctly. Assuming that the list of moves, let's call it possible_moves, contains the moves possible right now and that the dictionary scores contains the scores for all moves, even the impossible ones, you can issue:

max_score, max_move = max((scores[move], move) for move in possible_moves)

... or if you don't need the score:

max_move = max(possible_moves, key=scores.get)

How to iterate through a dictionary in Python?, There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list. There is also items() method of dictionary object which returns list of tuples, each tuple having key and value. Python: Iterate over list of tuples; Print version number of Python module; Python: Repeat the same random numbers using seed; Python: split command line into pieces as the shell does - shlex.split() Python context tools - cwd, tmpdir; Python and PostgreSQL; RPC with Python using RPyC; Python: Fermat primality test and generating co-primes

You can use max with dict.get:

possible_moves = [(2, 1), (2, 2), (2, 3), (3, 1), (4, 5), (5, 2),
                  (5, 3), (6, 0), (6, 2), (7, 1), (0, 2), (0, 1)]

scores = {(0,0): 10000, (0,1): -3000, (0,2): 1000, (0,3): 800}

res = max(possible_moves, key=lambda x: scores.get(x, 0))  # (0, 2)

This assumes moves not found in your dictionary have a default score of 0. If you can guarantee that every move is included as a key in your scores dictionary, you can simplify somewhat:

res = max(possible_moves, key=scores.__getitem__)

Note the syntax [] is syntactic sugar for __getitem__: if the key isn't found you'll meet KeyError.

Iterating over dictionaries using 'for' loops, key-value pairs, in Python 2 use for k,v in s. iteritems() , and in Python 3 for k,v in s. Iterate Through Tuple Elements Using For Loop in Python. You can perform the loop over the tuple elements using the for loop of Python. The for loop iterate each element of the tuple and print the elements in every single line. The elements can be of any type like string or integers.

If d is a dict, iterator of d generates keys. d.items() generates key-value pairs. So:

for move, value in moves_values.items():

How I can convert a Python Tuple into Dictionary?, object which returns list of tuples, each tuple having key and value. Varun August 5, 2018 Python Tuple: Different ways to create a tuple and Iterate over it 2018-08-05T09:41:09+05:30 Python, Tuple No Comment In this article we will discuss what is tuple, how its different from list, different ways to create a tuple and iterate over it.

possibleMoves=[(2, 1), (2, 2), (2, 3), (3, 1), (4, 5), (5, 2),(0, 3),(5, 3), (6, 0), (6, 2), (7, 1),(0,2)]
movevalues={(0,0): 10000, (0,1): -3000, (0,2): 1000, (0,3): 800}
def func():
    my_value=0
    for i in range(len(possibleMoves)):
        for k,v in movevalues.items():
            if possibleMoves[i]==k and v>my_value:


                my_value=v
    return my_value
maxValue=func()
print(maxValue)

How to Iterate Through a Dictionary in Python – Real Python, Once you know this, you can use tuple unpacking to iterate through the keys and values of the dictionary you are working with. To achieve this, you just need to  Easiest way is to employ two nested for loops. Outer loop fetches each tuple and inner loop traverses each item from the tuple. Inner print() function end=’ ‘ to print all items in a tuple in one line. Another print() introduces new line after each tuple.

Iterate over a dictionary in Python, There are multiple ways to iterate over a dictionary in Python. Iterate through all keys; Iterate through all values; Iterate through all key, value pairs Python | Ways to iterate tuple list of lists · Python | Pretty Print a dictionary with dictionary value  The object returned by .keys () here provided a dynamic view on the keys of a_dict. This view can be used to iterate through the keys of a_dict. To iterate through a dictionary in Python by using .keys (), you just need to call .keys () in the header of a for loop: >>>.

Python, In this method, we just iterate through the each dictionary item and get it's key's elements into a list. filter_none. edit close. play_arrow. link brightness_4 code  There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys () list. >>> D1 = {1:'a', 2:'b', 3:'c'} >>> for k in D1.keys(): print (k, D1[k]) 1 a 2 b 3 c.

Learn to Program using Python: Using Tuples as Keys, examples/python/iterate_list_of_tuples.py. pair = [; ('fname', 'Foo'),; ('lname', 'Bar'),​; ('email', 'foo@bar.com'),; ]; for p in pair: print('{} : {}'.format(p[0], p[1])); for p in  There are different ways to iterate through a tuple object. The for statement in Python has a variant which traverses a tuple till it is exhausted. It is equivalent to foreach statement in Java. Its syntax is −

Comments
  • I need a list of possible moves, because I'm playing a game and I have to return the best move.
  • @Orbit09 yes, I meant that you don't need it for the task of finding the best move if you have a dictionary as shown.
  • Yes, I understand, I can find the best move in the dictionary using your hack, but then I still have to check if the found move is possible anyway.
  • @Orbit09 I think I understand now. It would have been easier if we had the full dictionary of scores. The edited answer should work for you, but I can't check the result because you truncated the dict in your question.
  • Great, it works perfect, thanks! If you want the full values dictionary, it is from the game Reversi: [google.cz/…
  • As far as I understand the question now, the 0 is not necessary as a fallback value because scores is expected to contain all the fields of the board. If it does not, maybe -1 or float('-inf') would be a better fallback value in case there can be zero-point moves. In any case, very similar to my last edit -> +1