切片在python中使用for抛出一个列表

时间:2017-09-21 12:41:00

标签: python json

我有以下列表,它实际上是来自python的字典:

{"Age": {"1": 72, "0": 86, "3": 56, "2": 56, "4": 55}, "Weight": {"1": 71, "0": 70, "3": 39, "2": 61, "4": 54}, "Animal": {"1": "Cat", "0": "Dog", "3": "Horse", "2": "Monkey", "4": "mice"}}

如何将此切片以获得3个列表? 我想得到这样的东西:

Age = {"1": 72, "0": 86, "3": 56, "2": 56, "4": 55}
Weight =  {"1": 71, "0": 70, "3": 39, "2": 61, "4": 54}
Animal = {"1": "Cat", "0": "Dog", "3": "Horse", "2": "Monkey", "4": "mice"}

我知道我应该像这样使用:

for k, v in Age.items():
 print v

但是如何为3个列表执行此操作?如何以我想要的方式分配它: weight = {...},animal = {...}

4 个答案:

答案 0 :(得分:1)

只需将每个必需的密钥分配到变量中:

combined = {"Age": {"1": 72, "0": 86, "3": 56, "2": 56, "4": 55}, "Weight": {"1": 71, "0": 70, "3": 39, "2": 61, "4": 54}, "Animal": {"1": "Cat", "0": "Dog", "3": "Horse", "2": "Monkey", "4": "mice"}}

age = combined['Age']
weight = combined['Weight']
animal = combined['Animal']

print age
print weight
print animal

给你:

{'1': 72, '0': 86, '3': 56, '2': 56, '4': 55}
{'1': 71, '0': 70, '3': 39, '2': 61, '4': 54}
{'1': 'Cat', '0': 'Dog', '3': 'Horse', '2': 'Monkey', '4': 'mice'}

答案 1 :(得分:0)

您对数据结构使用了错误的命名。 你所指的是一个字典而不是列表。但对于提到的问题。以下是一个解决方案。

input_dict = {"Age": {"1": 72, "0": 86, "3": 56, "2": 56, "4": 55}, "Weight": {"1": 71, "0": 70, "3": 39, "2": 61, "4": 54}, "Animal": {"1": "Cat", "0": "Dog", "3": "Horse", "2": "Monkey", "4": "mice"}}
for k,v  in input_dict.items():
    vars()[k] = v

您现在可以打印变量。

print Age
{'1': 72, '0': 86, '3': 56, '2': 56, '4': 55}
print Weight
{'1': 71, '0': 70, '3': 39, '2': 61, '4': 54}
print Animal
{'1': 'Cat', '0': 'Dog', '3': 'Horse', '2': 'Monkey', '4': 'mice'}

根据@Eric Duminil的建议修改答案

答案 2 :(得分:0)

您的数据格式非常奇怪,使得迭代和查找比必要更加困难。

这是将其转换为更简单的数据格式的一种方法。它仍然是一个决定词。但是,迭代和查找应该更容易:

weird_data = {"Age": {"1": 72, "0": 86, "3": 56, "2": 56, "4": 55}, "Weight": {"1": 71, "0": 70, "3": 39, "2": 61, "4": 54}, "Animal": {"1": "Cat", "0": "Dog", "3": "Horse", "2": "Monkey", "4": "mice"}}

data = {name:{
        'id' : int(i),
        'age': weird_data["Age"][i],
        'weight': weird_data["Weight"][i]
    } for i,name in weird_data["Animal"].items()}

print(data)
#{'Cat': {'age': 72, 'id': 1, 'weight': 71},
# 'Dog': {'age': 86, 'id': 0, 'weight': 70},
# 'Horse': {'age': 56, 'id': 3, 'weight': 39},
# 'Monkey': {'age': 56, 'id': 2, 'weight': 61},
# 'mice': {'age': 55, 'id': 4, 'weight': 54}}

举个例子:

>>> list(data)
['Cat', 'Dog', 'Horse', 'Monkey', 'mice']
>>> [data[animal]['age'] for animal in data]
[72, 86, 56, 56, 55]
>>> data['Dog']['weight']
70

答案 3 :(得分:0)

让我们说你问题中的字典用

表示
dictionary = {
        "Age": {"1": 72, "0": 86, "3": 56, "2": 56, "4": 55},
        "Weight": {"1": 71, "0": 70, "3": 39, "2": 61, "4": 54},
        "Animal": {"1": "Cat", "0": "Dog", "3": "Horse", "2": "Monkey","4":"mice"}
}

您可以创建如下函数: -

def split_dictionary(Age, Weight, Animal):
    return Age, Weight, Animal

然后简单地调用这个函数: -

Age, Weight, Animal = split_dictionary(**dictionary)