简体   繁体   中英

How can i unpack a list of dicts. in python?

The output of my code is a list of dictionaries and I want to unpack this list and print each dictionary alone in one line and tried the join method but I couldn't work with it and I also want to erase the single quote from text, I just want the text to appear only and i can't do that. here's a sample of the list that i'm workin' with:

[{'نوع البطولة': 'الدوري المصري', 'الفريق الأول': 'المصري', 'الفريق الثانى': 'المقاولون العرب', 'وقت المباراة': '21-12-2022 - 17:00', 'النتيجة': '- - -'}, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'المنصورة', 'الفريق الثانى': 'نبروه', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'}, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'الحمام', 'الفريق الثانى': 'المجد السكندري', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'}, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'أبو قير للأسمدة', 'الفريق الثانى': 'هلال مطروح', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'}]

i'm expecting to get a text like this:

'نوع البطولة': 'الدوري المصري', 'الفريق الأول': 'المصري', 'الفريق الثانى': 'المقاولون العرب', 'وقت المباراة': '21-12-2022 - 17:00', 'النتيجة': '- - -'
 نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'المنصورة', 'الفريق الثانى': 'نبروه', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'
, {'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'الحمام', 'الفريق الثانى': 'المجد السكندري', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'
 'نوع البطولة': 'دوري الدرجة الثانية المصري', 'الفريق الأول': 'أبو قير للأسمدة', 'الفريق الثانى': 'هلال مطروح', 'وقت المباراة': '21-12-2022 - 14:30', 'النتيجة': '- - -'

If I understand correctly, you want to print the entire array of dictionaries on one line . To do this, you can loop through the initial array, and print them, but specify an ending with the print statement, and don't let it end with a newline ( \n ).

In Python:

list = ['str1', 'str2', 'str3']
for i in list:
    print(i, end=' ')

If you do not want a space in-between each element, make the print statement print(i, end='') .

There's nothing built-in that prints a dictionary without its {} delimiters, so you need write your own formatter.

def format_dict(d):
    return ', '.join(f'{repr(key)}: {repr(value)}' for key, value in d.items())

for d in list_of_dicts:
    print(format_dict(d))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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