繁体   English   中英

从列表数组dic python提取

[英]Pulling from a list array dic python

我乱抛垃圾地阅读了我从该数组中获取键的所有帖子。 我可以获取要打印dic的数组,但我似乎无法拉键。 我需要它来打印名字和姓氏。 学习python但似乎无法做到这一点。

students = [
     {'first_name':  'Michael', 'last_name' : 'Jordan'},
     {'first_name' : 'John', 'last_name' : 'Rosales'},
     {'first_name' : 'Mark', 'last_name' : 'Guillen'},
     {'first_name' : 'KB', 'last_name' : 'Tonel'}
]


for i in students:


    first = [students[i].get('first_name') in students.values()] + [students[i].get('last_name') in students.values()]
    second= [students[i].get('first_name') in students.values()] + [students[i].get('last_name') in students.values()]
    third=  [students[i].get('first_name') in students.values()] + [students[i].get('last_name') in students.values()]
    four=   [students[i].get('first_name') in students.values()] + [students[i].get('last_name') in students.values()]



    print first, second, third, fourth

在遍历数组时,您的i已经是元素

for i in students:
  print([i['first_name'], i['last_name']])

如果我正确理解这一点,则看起来您只想分别在字符串中存储名字和姓氏。

students = [
    {'first_name':  'Michael', 'last_name' : 'Jordan'},
    {'first_name' : 'John', 'last_name' : 'Rosales'},
    {'first_name' : 'Mark', 'last_name' : 'Guillen'},
    {'first_name' : 'KB', 'last_name' : 'Tonel'}
]
first = students[0]["first_name"] + " " + students[0]["last_name"]
second = students[1]["first_name"] + " " + students[1]["last_name"]
third = students[2]["first_name"] + " " + students[2]["last_name"]
fourth = students[2]["first_name"] + " " + students[2]["last_name"]
print first, second, third, fourth

并给出输出

Michael Jordan John Rosales Mark Guillen Mark Guillen

这将在变量中存储字典值的名字和姓氏。

我必须使用列表符号来获取我想要的字典的索引,然后使用键访问该值。 如果您看第一行。 students[0]["first_name"]数组符号[0]指的是{'first_name': 'Michael', 'last_name' : 'Jordan'}这本字典。 [“ first_name”]允许我访问按键排序的key_value。 在我们的例子中是'Michael'

暂无
暂无

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

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