Python's two-dimension dictionary definition and implementation method, twodimensioncode

Source: Internet
Author: User

Python's two-dimension dictionary definition and implementation method, twodimensioncode

This article describes how to define and implement the "two-dimension dictionary" dictionary in Python. We will share this with you for your reference. The details are as follows:

Dict in Python allows quick search. Is there a two-dimensional dictionary like an array with two-dimensional arrays? For example, when I need to search for two keywords. 2D dict

dict_2d = {'a': {'a': 1, 'b': 3}, 'b': {'a': 6}}

And

dict_2d['a']['b']

. However, adding a new "key-value" pair is complicated. For one-dimensional dictionaries, you can use

dict_1d = dict()dict_1d['a'] = 1

Or

dict_1d.update({'a': 1})

. However, when "2-D" dictionary adds a new "key-value" pair

dict_2d['a']['c'] = 8

. Because the two-layer keys and values of the two-dimensional dictionary are confused, you need to determine whether the first key already exists. You can use a function to add a two-dimensional dictionary:

def addtwodimdict(thedict, key_a, key_b, val):  if key_a in adic:    thedict[key_a].update({key_b: val})  else:    thedict.update({key_a:{key_b: val}})

For example, it can be used to find the distance between cities.

mapdict = dict()addtwodimdict(mapdict, 'Beijing', 'Guangzhou', 1897)addtwodimdict(mapdict, 'Chengdu', 'Guangzhou', 1243)addtwodimdict(mapdict, 'Guangzhou', 'Shanghai', 1212)addtwodimdict(mapdict, 'Beijing', 'Chengdu', 1516)addtwodimdict(mapdict, 'Chengdu', 'Shanghai', 1657)addtwodimdict(mapdict, 'Beijing', 'Shanghai', 1075)print 'The distance between Chengdu and Guangzhou is ',mapdict['Chengdu']['Guangzhou']

It is quite convenient.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.