簡體   English   中英

如何在一行中打印您選擇的字典中的值? 在 Python 中

[英]How to print values from dictionary of your choice in a single line ? IN PYTHON

假設這是一本字典: {'name': 'Instagram', 'follower_count': 346, 'description': 'Social media platform', 'country': 'United States'}

我想要我的輸出,比如: Instagram, Social media platform, United States

我如何實現這一目標?

我想這就是你要找的嗎?

import operator

items_getter = operator.itemgetter('name', 'description', 'country')
print(', '.join(items_getter(dictionary)))

使用條件中的鍵來消除您想要消除的任何值

for i in thisdict:
    if i == "follower_count":
        continue
    else:
        print(thisdict[i])

或者您也可以使用 .items 方法獲取鍵值,然后繼續

for k,v in thisdict.items():
    if k=="follower_count":
        continue
    else:
        print(v)

這是您獲得所需內容的最簡單方法:

dct = {
    'name': 'Instagram', 
    'follower_count': 346, 
    'description': 'Social media platform', 
    'country': 'United States'
}

print(f'{dct['name']}, {dct['description']}, {dct['country']}')

輸出:

Instagram, Social media platform, United States

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM