简体   繁体   English

访问字典中的值

[英]Accessing values in dictionary

there are no problems with the code - it is running just fine, however, I'm not fully understanding why it is working.代码没有问题 - 它运行得很好,但是,我不完全理解它为什么工作。

From my understanding, if I provide only 1 variable in the for loop - it automatically stores "keys" of the dictionary (which it did in the 1st print statement).据我了解,如果我在 for 循环中仅提供 1 个变量 - 它会自动存储字典的“键”(它在第一个打印语句中执行)。 My question is, how come the last print statement " + favorite_languages[name].title() + "!") -- prints the actual values?我的问题是,最后一个打印语句" + favorite_languages[name].title() + "!")怎么来打印实际值?

Were the keys not stored in "name" in the for loop?键不是存储在 for 循环中的“名称”中吗? I'm reading the code and to me it reads - Hey phil, I see your favorite language is phil!我正在阅读代码,对我来说它是 - 嘿 phil,我看到你最喜欢的语言是 phil!

Could anyone explain?谁能解释一下?

favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }


friends = ['phil', 'sarah']
for name in favorite_languages:
 print(name.title())
 if name in friends:
     print("Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")

Dictionaries work like this:字典是这样工作的:

{ KEY : VALUE }

In the example在示例中

{'Phil':'python'}

Phil is the key, and not a value.菲尔是关键,而不是价值。 so accessing ['Phil'] outputs the value associated with that key which isn't 'Phil' but 'python'.因此访问 ['Phil'] 会输出与该键关联的值,该键不是“Phil”而是“python”。

I think you are confused because implicitly you expected a format more like this:我认为你很困惑,因为你隐含地期望一种更像这样的格式:

favorite_languages = (
{name: 'Phil', language: 'Python'},
{name: 'sarah', language: 'c'}
)

Which is a list of dicts!这是一个字典列表!

Name is the key for the dictionary名称是字典的键

favorite_languages = {
 'jen': 'python',
 'sarah': 'c',
 'edward': 'ruby',
 'phil': 'python',
 }

On which you are iterating.您正在迭代的。 If you execute a print in the foor loop you'll see what name is:如果你在 foror 循环中执行打印,你会看到名字是什么:

for name in favorite_languages:
    print(name.title())
    if name in friends:
        print(name) # here
        print("Hi " + name.title() + ", I see your favorite language is " + favorite_languages[name].title() + "!")

To understand better, try to execute this code:为了更好地理解,请尝试执行以下代码:

for key, value in favorite_languages.items():
    print("This is the key {}. This is the value {}".format(key, value))

# This is the key jen. This is the value python
# This is the key sarah. This is the value c
# This is the key edward. This is the value ruby
# This is the key phil. This is the value python

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

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