简体   繁体   English

如何获取字典 python 的值?

[英]How to get the values of dictionary python?

I have the below python dictionary stored as dictPython我将以下 python 字典存储为dictPython

{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale .我需要获取vanityName, localizedName的值以及来自name->localizedname->preferredLocale的值。

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']) .我尝试dictPython.keys()并返回dict_keys(['paging', 'elements'])

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).我还尝试dictPython.values() ,它返回了括号 ({}) 内的内容。

I need to get [vv, ViV, ViV, US, en]我需要得到[vv, ViV, ViV, US, en]

I am writing this in a form of answer, so I can get to explain it better without the comments characters limit我正在以答案的形式写这篇文章,所以我可以在没有评论字符限制的情况下更好地解释它

  • a dict in python is an efficient key/value structure or data type for example dict_ = {'key1': 'val1', 'key2': 'val2'} to fetch key1 we can do it in 2 different ways dict中的字典是一种有效的键/值结构或数据类型,例如dict_ = {'key1': 'val1', 'key2': 'val2'}来获取key1我们可以通过两种不同的方式来完成
    1. dict_.get(key1) this returns the value of the key in this case val1 , this method has its advantage, that if the key1 is wrong or not found it returns None so no exceptions are raised. dict_.get(key1)在这种情况下返回键的值val1 ,此方法有其优点,如果 key1 错误或未找到,则返回None因此不会引发异常。 You can do dict_.get(key1, 'returning this string if the key is not found')您可以执行dict_.get(key1, 'returning this string if the key is not found')
    2. dict_['key1'] doing the same .get(...) but will raise a KeyError if the key is not found dict_['key1']执行相同的.get(...)但如果找不到密钥,则会引发KeyError

So to answer your question after this introduction, a dict can be thought of as nested dictionaries and/or objects inside of one another to get your values you can do the following因此,为了在介绍之后回答您的问题,可以将dict视为嵌套的字典和/或彼此内部的对象以获得您的值,您可以执行以下操作

# Fetch base dictionary to make code more readable
base_dict = dict_["elements"][0]["organizationalTarget~"]
# fetch name_dict following the same approach as above code
name_dict = base_dict["name"]
localized_dict = name_dict["localized"]
preferred_locale_dict = name_dict ["preferredLocale"]

so now we fetch all of the wanted data in their corresponding locations from your given dictionary, now to print the results, we can do the following所以现在我们从给定的字典中获取相应位置的所有想要的数据,现在要打印结果,我们可以执行以下操作

results_arr = []
for key1, key2 in zip(localized_dict, preferredLocale_dict):
    results_arr.append(localized_dict.get(key1))
    results_arr.append(preferred_locale_dict.get(key2))

print(results_arr)

What about:关于什么:

dic = {
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",
        },
    ],
}
base = dic["elements"][0]["organizationalTarget~"]
c = base["name"]["localized"]
d = base["name"]["preferredLocale"]
output = [base["vanityName"], base["localizedName"]]
output.extend([c[key] for key in c])
output.extend([d[key] for key in d])

print(output)

outputs:输出:

['vv', 'ViV', 'ViV', 'US', 'en']

So something like this?那么像这样的东西?

[[x['organizationalTarget~']['vanityName'],
  x['organizationalTarget~']['localizedName'],
  x['organizationalTarget~']['name']['localized']['en_US'],
  x['organizationalTarget~']['name']['preferredLocale']['country'],
  x['organizationalTarget~']['name']['preferredLocale']['language'],
 ] for x in s['elements']]

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

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