所以我希望此代码以不同的方式打印:
Python代码:
employees = {123: 'Bob', 124: 'Susan', 128: 'Abby', 125: 'Henry', 126: 'Edward', 127: 'James'}
for key in employees.keys():
print("Employees Numbers: ", key)
for value in employees.values():
print("Employee Names: ", value)
打印为:
Employees Numbers: 123
Employees Numbers: 124
Employees Numbers: 128
Employees Numbers: 125
Employees Numbers: 126
Employees Numbers: 127
Employee Names: Bob
Employee Names: Susan
Employee Names: Abby
Employee Names: Henry
Employee Names: Edward
Employee Names: James
希望将其打印为:
Employee Numbers: 123, 124, 128, 125, 126, 127
Employee Names: Bob, Susan, Abby, Henry, Edward
答案 0 :(得分:1)
您可以像这样循环浏览这些键:
print('Employee Numbers: {}'.format(', '.join(str(num) for num in employees.keys())))
然后类似地输入名称:
print('Employee Names: {}'.format(', '.join(name for name in employees.values())))
答案 1 :(得分:0)
您可以循环浏览字典并使用格式化的字符串进行显示
>>> employees = {123: 'Bob', 124: 'Susan', 128: 'Abby', 125: 'Henry', 126: 'Edward', 127: 'James'}
>>> print('Employee Numbers: {}'.format(', '.join(str(key) for key in employees.keys())))
Employee Numbers: 128, 123, 124, 125, 126, 127
>>> print('Employee Names: {}'.format(', '.join(value for value in employees.values())))
Employee Names: Abby, Bob, Susan, Henry, Edward, James
答案 2 :(得分:0)
首先将keys
和values
存储到单独的lists
中,然后使用join
运算符将它们填充到由string
分隔的comma
中。
对于员工编号,您需要执行一个额外的步骤,将编号转换为strings
(因为join
仅在string
上起作用)
employees = {123: 'Bob', 124: 'Susan', 128: 'Abby', 125: 'Henry', 126: 'Edward', 127: 'James'}
numbers = list(employees.keys())
names = list(employees.values())
print("Employee Keys : ",', '.join([str(i) for i in numbers]))
print("Employee Names : ",', '.join(names))
答案 3 :(得分:0)
#!/usr/bin/env python
def main():
employees = {123: 'Bob', 124: 'Susan', 128: 'Abby', 125: 'Henry', 126: 'Edward', 127: 'James'}
print("employees ids:", ", ".join([str(x) for x in employees]))
print("employees names:", ", ".join([str(x) for x in employees.values()]))
if __name__ == '__main__':
main()
输出:
employees ids: 123, 124, 128, 125, 126, 127
employees names: Bob, Susan, Abby, Henry, Edward, James
答案 4 :(得分:-1)
employees = {123: 'Bob', 124: 'Susan', 128: 'Abby', 125: 'Henry', 126: 'Edward', 127:
'James'}
a=list(employees.keys())
str1=", ".join(str(e) for e in a)
print("Employee Numbers:",str1)
b=list(employees.values())
str2=", ".join(b)
print("Employee Names:",str2)