简体   繁体   English

具有多个值的Python Dict键

[英]Python Dict Key with Multiple Values

I'm learning about dictionaries, and I know I could do this by creating two more dictionaries, but for brevity's sake, I wanted to make the code a bit more concise than having to create two more dict (granted, in the end, everything I wrote out for this dict would have to be written in the other dicts), so I guess I'm more curious than anything. 我正在学习字典,我知道我可以通过再创建两个字典来做到这一点,但是为了简洁起见,我想使代码更加简洁,而不是必须再创建两个字典(最终,所有内容我写的这个字典必须写在其他字典中,所以我想我比什么都好奇。 And I know that I shouldn't be using a for-loop, but I don't know another way, and as far as LPTH sucking, I had to start somewhere. 而且我知道我不应该使用for循环,但是我不知道另一种方式,就LPTH而言,我不得不从某个地方开始。

question 1: How can I get this to cycle through each state/abbrev/city? 问题1:如何让它遍历每个州/缩写/城市? Would I have to just make multiple dicts, or a series of lists and use those? 我是否只需要做多个字典或一系列列表并使用它们? question2: Why does this code run the for-loop 11 times? 问题2:为什么此代码会运行for循环11次?

states1 = {
    '1': 'Oregon', 'a': 'OR','population': '1000',
    '2': 'Florida', 'b': 'MI', 'population': '1000',
    '3': 'California', 'c': 'CA', 'population': '1000',
    '4': 'NewYork', 'd': 'NY', 'population': '1000',
    '5': 'Michigan','e': 'MI','population': '1000',
}

for city, pop, in states1.items():
    print "%s has the abbreviation %s and a population of %s" %states1['1'], states1['a'], states1['population'])

Ideally, you'd have a homgonous datastructure -- eg a list of dict 1 . 理想情况下,您将拥有一个统一的数据结构-例如dict 1 list Each dict would hold the information about a particular state: 每个dict将保存有关特定状态的信息:

states1 = [
  {'name': 'Oregon', 'abbrev': 'OR', 'population': 1000},
  {'name': 'Florida', 'abbrev': 'FL', 'population': 1000},
  ...,
]

Now your loop looks like this: 现在,您的循环如下所示:

for state in states1:
    print print "%s has the abbreviation %s and a population of %s" % (state['name'], states['abbrev'], states['population'])

The benefit here is hopefully clear. 希望这里的好处是显而易见的。 For any given state, you retrieve the related information the same way (the state's name is always reachable via the 'name' key). 对于任何给定的州,您都可以以相同的方式检索相关信息(始终可以通过'name'键访问该州的名称)。

If you ever need a mapping of state names (eg you want to look up a bunch of state's populations by their abbreviation), you can do that pretty easily by creating a dict... 如果您需要映射州名(例如,您想通过州名的缩写查找一堆州的人口),则可以通过创建字典来轻松地做到这一点。

abbrev_to_state = {state['abbrev']: state for state in states1}
florida_data = abbrev_to_state['FL']
new_hampshire_data = abbrev_to_state['NH']
...

1 There are other options here too... You could use a custom class, but this also seems like a good candidate for a list of collections.namedtuple assuming you aren't planning on mutating the data. 1这里也有其他选项...您可以使用自定义类,但是如果您不打算对数据进行突变,这似乎也是collections.namedtuple列表的不错选择。

You could make each value be a list. 您可以使每个值成为一个列表。

I do not understand what exactly you want to achieve, but the easy way would be: 我不知道您到底想实现什么,但是简单的方法是:

states1 = {
1: ["Oregon", "OR", 1000]
2: ["Florida", "FL", 1000]
3: ["Pythonville", "PY", 1000]
4: ["Dictville", "DI", 1000]
}

Another thing you could look up is named tuple , it is one of my favorite data structures for when you want to quickly organize data. 您可以查找的另一件事称为tuple ,它是我想要快速组织数据时最喜欢的数据结构之一。

from collections import namedtuple

CityInfo = namedtuple("CityInfo", ["Name", "Abbr", "Pop"])

states1 = {
            1: CityInfo("Oregon", "OR", 1000),
            2: CityInfo("Florida", "FL", 1000),
            3: CityInfo("Pythonville", "PY", 1000),
            4: CityInfo("Dictville", "DI", 1000)
            }

for city in states1.values():
    print("{} has the abbreviation {} and a population of {}".format(city.Name, city.Abbr, city.Pop))

When I run it as you recommended me to (below), it spits out 当我按照您的建议运行(如下)时,它吐出了

Michigan has the abbreviation MI and a population of 1000
Michigan has the abbreviation MI and a population of 1000
Michigan has the abbreviation MI and a population of 1000

not sure why it's continually doing that, I would have guessed if it was for some reason to choose a totally random state because it's a dictionary that it would change the state each time, with occasional duplicates. 不知道为什么它会持续这样做,我会猜测是否由于某种原因选择了一个完全随机的状态,因为这是一本字典,每次都会更改状态,偶尔会重复。

states1 = {
    'state': 'Oregon', 'abbrev': 'OR','population': '10000',
    'state': 'Florida', 'abbrev': 'MI', 'population': '1000',
    'state': 'California', 'abbrev': 'CA', 'population': '1000',
    'state': 'NewYork', 'abbrev': 'NY', 'population': '1000',
    'state': 'Michigan','abbrev': 'MI','population': '1000',
}

for city, pop, in states1.items():
    print "%s has the abbreviation %s and has a population of %s" % (states1['state'], states1['abbrev'], states1['population'])

Another example of how you could structure your data depending on your needs. 另一个示例,说明如何根据需要构造数据。

states1 = {
'Oregon': {'abrv': 'OR','population': '1000'},
'Florida':{ 'abrv': 'MI', 'population': '1000'},
'California':{'abrv': 'CA', 'population': '1000'},
'NewYork':{'abrv': 'NY', 'population': '1000'},
'Michigan':{'abrv': 'MI','population': '1000'}}



for state in states1:
  print "%s has the abbreviation %s and a population of %s" %(state, states1[state]['abrv'], states1[state]['population'])

Just saw the last post, that makes a lot of sense. 刚刚看了最后一篇文章,那很有道理。 As far as how this could be useful, I don't know, it was just something I wanted to do, have three values to one key. 至于这怎么用,我不知道,那只是我想做的,对一个键有三个值。 I'm sure in the future I could take the info from a website or database and have it create pairs, like actors to characters played, but maybe not. 我敢肯定,将来我可以从网站或数据库中获取信息,并将其创建成对,例如从演员到扮演的角色,但也许不是。 It was just something I was annoyed I couldn't figure out on my own. 只是让我烦恼,我无法自己弄清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM