4

I am finding it difficult to iterate through a dictionary in python.

I have already finished learning via CodeAcademy and solo learn but still find it tough to go through a dictionary.

Are there any good resources other than official documentation of Python to learn more and given in lucid language where I can be more comfortable with python.

Roland
  • 127,288
  • 10
  • 191
  • 288
niksy
  • 323
  • 1
  • 4
  • 9

8 Answers8

9

Lots of different documentations and tutorial resources available for Python online, almost each of them are helpful depending upon your need. But most reliable documentation is official documentation of Python website.

Also please watch youtube videos of the same, many videos of practical implementation of dictionaries and other Python constructs are available in easy to understandable manner.

Here is sample program for dictionary implementation:

my_dict = {'name':'Deadpool', 'designation': 'developer'}
print(my_dict)
Output: { 'designation': developer, 'name': Deadpool}

# update value
my_dict['designation'] = 'sr developer'

#Output: {'designation': sr developer, 'name': Deadpool}
print(my_dict)

# add an item to existing dictionary
my_dict['address'] = 'New York'  
print(my_dict)
# Output: {'address': New York, 'designation': sr developer, 'name': Deadpool}
Tonechas
  • 13,398
  • 16
  • 46
  • 80
Divyanshu
  • 91
  • 4
2

If you are using Python 2

for key, value in d.iteritems():

For Python 3

for key, value in d.items():

As usual the documentation is the best source for information Python 2 Python 3

Colwin
  • 2,655
  • 3
  • 25
  • 25
2

Its irony, although you are looking for alternative resources but trust me no documentation or reference book can beat the official Python documentation as it is always the latest and closest to the python language.

Browse through different versions on the main python website.

Dictionary : https://docs.python.org/3/tutorial/datastructures.html#dictionaries

Here is one more website that has lot of Python resources (even for specific occupations) but as I told before nothing can beat official Python documentation.

One more link : python wiki.

Understanding dictionary, below is from official python documentation website ...

## dictionary initialization
>>> tel = {'jack': 4098, 'sape': 4139}

## set value for a key (either existing or new)
>>> tel['guido'] = 4127

## print dictionary
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}

## get value for an existing key
>>> tel['jack']
4098

## delete a key from dictionary
>>> del tel['sape']

## add a new key with value
>>> tel['irv'] = 4127

## print dictionary
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}

## get all keys in dictionary
>>> list(tel.keys())
['irv', 'guido', 'jack']

## get all keys in dictionary (sorted)
>>> sorted(tel.keys())
['guido', 'irv', 'jack']

## check if a key exists in dictionary
>>> 'guido' in tel
True

## check if a key exists in dictionary
>>> 'jack' not in tel
False

## Finally iterating thru dictionary
for key, value in tel.items():
    print(key, value)
JRG
  • 4,037
  • 3
  • 23
  • 34
1
# In Python 3.x

hash={'a': 1, 'b': 2}

for k in hash:
    print (str(k) + "," + str(hash[k]))

# OR
for key, value in hash.items():
    print (str(key) + ',' + str(value))

# OR
for key, value in {'a': 1, 'b': 2}.items():
    print (str(key) + ',' + str(value))

# OR
for tup in hash.items():
    print (str(tup[0]) + ',' + str(tup[1]))
Sachin S
  • 396
  • 8
  • 17
1
Dict = { 1 : 'Suri' , 'Fname' : 'Sam' , 'Lname' : 'Saiksas' , 'village' : 'AKP' }
print ( Dict )

Built-in dict method to create a dictionary:

Dict2 = dict ( { 1 : 'john' , 2 : 'Pam' , 3 : 'google' } )
print ( Dict2 )

Using pairs to create a dictionary:

Dict3 = dict ( [ ('1' , 'Techies') , (2 , 'For') ] )
print ( Dict3 )

Create a dictionary out of other data structures - list of tuples prints only one value if there are any duplicate tuples in the list:

list1 = [ (2 , 3) , (4 , 5) , (4 , 5) ]
print ( dict ( list1 ) )

Assign values to Dictionaries:

exDict = { }
exDict [ 'Key_1' ] = 'Welcome'
exDict [ 'Key_2' ] = 'Good'
exDict [ 'Key_3' ] = 'Morning'
exDict [ 'Key_4' ] = 'Deo'
print ( exDict )

Assign a value set to a key - Assigning multiple values to a single key:

exDict[ 'Key_1' ] = 'Welcome' , 'Mr' , 'Graham'
print ( exDict )

Fetching a value from a dictionary using Get Method:

print ( '\n' , exDict.get ( 'Key_4' ) )
print ( '\n' )

print ( "|{0}|,|{1}|,{2}|".format ( exDict [ 'Key_1' ] , exDict [ 'Key_2' ] , exDict [ 'Key_3' ] ) )

Deleting items from the dictionary:

print ( exDict.values ( ) )
exDict.pop ( 'Key_1' )
print ( "After popping an element " , exDict )
print ( '\n' , 'This is the copy of dict' , exDict.copy ( ) )
print ( '\n' )
print ( '\n' )

Delete an entire dict:

print ( exDict.values ( ) )
print ( '\n' )
print ( exDict.items ( ) )
exDict.clear ( )
print ( '\n' )
print ( exDict )
Gavriel Cohen
  • 4,355
  • 34
  • 39
0

You need to  check this out

HEAD FIRST PYTHON

http://www.headfirstlabs.com/books/hfpython/

This will change your life and make it interesting to learn PYTHON. You will grasp each concept of Python rather than mugging it up. This book has a very intuitive way of making you understand python.

This book has a detail explanation on Dictionary and other core concepts.

Ujjwal Roy
  • 500
  • 6
  • 9
  • Suggest linking to the subsection on dictionaries / iteration. – rmharrison Jul 13 '17 at 07:32
  • Since the book is not available freely.I'm leaving the section in the book where you can find the reference for dictionary. **Chapter 6 -> Use of dictionary to associate data (Page no 178)** – Ujjwal Roy Jul 13 '17 at 13:01
0

Dictionaries are the python equivalent of Hash table. It stores values as key-value pairs. Values can be any python objects whereas, keys need to immutable.

Below are some of the ways to iterate over a dictionary in python

# Iterating over the keys.
for k in dict:
for k in dict.keys():

#Iterating over the values.
for v in dict.values():

#Iterating over both the key and values.
for k,v in dict.items():
hyder47
  • 11
  • 2
0

I think it can be useful to learn Python dictionaries that have the same keys with different values.

dict1 = {"idno" : 101, "name" : "A"}

dict2 = {"idno" : 102, "name" : "B","contact_no" : 99999999999}
# if we have two dictionaries with the same keys and different values, in that case if we try to merge two dicts
# then values will be updated with the same key. 
# So that we cant access both dictinary's values.
# if you could see below code, using dict comprehension we can merge two dictionaries in single line 
merged_dict = {x : [dict1,dict2][x] for x in range(len([dict1,dict2]))}
print(merged_dict)

# if you want to update value then you can go with below code
merged_dict = {**dict1,**dict2}
print(merged_dict)
shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34