Programming in Python : Dictionaries

Dictionaries are another data type in python. It can be think as a unordered collection of keys associated with values. The keys can be numbers, strings, or tuples. An empty dictionary is denoted by ‘{ }’. We can view all keys by simply calling keys(). The dict() constructor is using to build a dictionary.

>>> dic = {‘one’:1,’two’:2,’three’:3,’four’:4,’five’:5}

>>> dic
{‘four’: 4, ‘three’: 3, ‘five’: 5, ‘two’: 2, ‘one’: 1}

>>> dic[‘six’] = 6

>>> dic
{‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4, ‘five’: 5, ‘one’: 1}

>>> del dic[‘five’]

>>> dic
{‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4, ‘one’: 1}

>>> dic[‘seven’] = 7

>>> dic
{‘seven’: 7, ‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4, ‘one’: 1}

>>> dic.key()

Traceback (most recent call last):
File “”, line 1, in
AttributeError: ‘dict’ object has no attribute ‘key’

>>> dic.keys()
[‘seven’, ‘six’, ‘three’, ‘two’, ‘four’, ‘one’]

>>> dic[‘seven’]
7
>>> dic[‘one’]
1

>>> ‘one’ in dic
True

>>> ‘three’ in dic
True

>>> ‘kjkk’ in dic
False

>>> del dic[‘one’]

>>> dic
{‘seven’: 7, ‘six’: 6, ‘three’: 3, ‘two’: 2, ‘four’: 4}

>>> dic.keys()
[‘seven’, ‘six’, ‘three’, ‘two’, ‘four’]

>>> dic.values()
[7, 6, 3, 2, 4]

>>> a=[(‘aass’,23),(‘iiii’,56),(‘dftj’,38)]

>>> a
[(‘aass’, 23), (‘iiii’, 56), (‘dftj’, 38)]

>>> dict(a)
{‘aass’: 23, ‘iiii’: 56, ‘dftj’: 38}

>>> b = dict(a)

>>> b
{‘aass’: 23, ‘iiii’: 56, ‘dftj’: 38}

>>> dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)
{‘jkhjkhk’: 3434, ‘jhjkhk’: 433, ‘iuijmkm’: 344343}

>>> c = dict(jhjkhk = 433,jkhjkhk = 3434,iuijmkm = 344343)

>>> c
{‘jkhjkhk’: 3434, ‘jhjkhk’: 433, ‘iuijmkm’: 344343}

Advertisement

Author: Abhilash

I'm Abhilash, a web developer who specializes in Ruby development. With years of experience working with various frameworks like Rails, Angular, Sinatra, Laravel, NodeJS, React and more, I am passionate about building robust and scalable web applications. Since 2010, I have been honing my skills and expertise in the Ruby on Rails platform. This blog is dedicated to sharing my knowledge and experience on topics related to Ruby, Ruby on Rails, and other subjects that I have worked with throughout my career. Join me on this journey to explore the exciting world of web development!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: