从字典中引用和打印值(Python)

时间:2018-07-13 06:40:19

标签: python python-3.x dictionary

下面的代码可以找到用户输入的地区所在的城市及其邮政编码。我已经将数据放入字典中,我想知道如何修改代码以从用户那里接收邮政编码,并输出其所在的地区和城市。

代码:

zipcode = {
    "Trap City": {
        "C District": 100,
        "D District": 103,
        "E District": 104,
        "S District": 105
    },
    "Zap City": {
        "R District": 200,
        "D District": 201
    },
    "Los City": {
        "X District": 207,
        "Y District": 208
    }
}

district=input('Enter your district: ')

for city in zipcode:
    if district in zipcode[city]:
        print(city,zipcode[city][district])

4 个答案:

答案 0 :(得分:0)

使用“邮政编码[city]”,您可以获取整个词典。我猜用户应该以String的形式输入区?

for city in zipcode:
    if district in list(zipcode[city].keys()):
        print(city,zipcode[city][district])

列表(邮政编码[city] .keys())为您提供了城市词典中的所有密钥,您可以根据这些密钥来检查地区。
对于Python 2.x,只需 zipcode [city] .keys()即可获取列表。

答案 1 :(得分:0)

只需用dict理解转换zipcode即可使其通过邮政编码索引:

{z: (c, d) for c, i in zipcode.items() for d, z in i.items()}

这将输出:

{100: ('Trap City', 'C District'), 103: ('Trap City', 'D District'), 104: ('Trap City', 'E District'), 105: ('Trap City', 'S District'), 200: ('Zap City', 'R District'), 201: ('Zap City', 'D District'), 207: ('Los City', 'X District'), 208: ('Los City', 'Y District')}

使用此新字典,您可以轻松地从给定的邮政编码中获取城市和地区。

答案 2 :(得分:0)

可以通过多种方式解决此问题,但是我制作了get_disctrict_and_city()函数,该函数具有一个参数postal_code并返回包含districtcity的元组:

zipcode = {"Trap City":{"C District": 100, "D District": 103, "E District": 104, "S District": 105},
       "Zap City":{"R District": 200, "D District": 201},
       "Los City": {"X District": 207, "Y District": 208}}

def get_disctrict_and_city(postal_code, data=zipcode):
    for city, districts in data.items():
        for district, code in districts.items():
            if code == postal_code:
                return district, city

postal_code=int(input('Enter postal code: '))
district, city = get_disctrict_and_city(postal_code)

print('District = {} City = {}'.format(district, city))

输出:

Enter postal code: 100
District = C District City = Trap City

答案 3 :(得分:0)

我对python不太了解,但是您可以在Google上搜索它。我会像您在R中一样做这件事。我通过谷歌搜索找到了以下内容:

import pandas as pd

def get_city_dist(num,dicts):
    s = pd.DataFrame(dicts)==num
    m = list(s.columns[s.any()]) + list(s.index[s.T.any()])
    return dict(zip(["city","District"], m))


get_dis_cit(103,zipcode)
Out[122]: {'city': 'Trap City', 'District': 'D District'}

get_dis_cit(100,zipcode)
Out[123]: {'city': 'Trap City', 'District': 'C District'}

get_dis_cit(200,zipcode)
Out[124]: {'city': 'Zap City', 'District': 'R District'}

get_dis_cit(208,zipcode)
Out[125]: {'city': 'Los City', 'District': 'Y District'}