Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python for key, value in dictionary

So as of now this is my code:

for keys, values in CountWords.items():
    val = values
    print("%s: %s \t %s: %s" % (keys, val, keys, val))

When this is printed it will output this the key and its value and then after a space the same thing. What I want to know is if I can get the second %s: %s to select the next key and value from the dictionary.

like image 999
willstaff Avatar asked Mar 31 '15 12:03

willstaff


People also ask

How do you get a value from a dictionary key Python?

In Python, you can get the value from a dictionary by specifying the key like dict[key] . In this case, KeyError is raised if the key does not exist. Note that it is no problem to specify a non-existent key if you want to add a new element.

How do you check if a key has a value in Python?

Check If Key Exists using has_key() method Using has_key() method returns true if a given key is available in the dictionary, otherwise, it returns a false. With the Inbuilt method has_key(), use the if statement to check if the key is present in the dictionary or not.

How do you check if a value is in a dictionary Python?

Check if a value exists in a dictionary: in operator, values() To check if a value exists in a dictionary, i.e., if a dictionary has/contains a value, use the in operator and the values() method. Use not in to check if a value does not exist in a dictionary.


1 Answers

Instead of trying to get next k-v pair, you can keep current k-v pair and use them on the next iteration

d = {'foo': 'bar', 'fiz': 'baz', 'ham': 'spam'}

prev_key, prev_value = None, None

for key, value in d.items():
    if prev_key and prev_value:
        print("%s: %s \t %s: %s" % (prev_key, prev_value, key, value))
    prev_key, prev_value = key, value

fiz: baz     foo: bar
foo: bar     ham: spam
like image 119
Rafis Gubaidullin Avatar answered Oct 04 '22 17:10

Rafis Gubaidullin