Home > OS >  Replace empty values in list of dictionaries by corresponding value
Replace empty values in list of dictionaries by corresponding value

Time:10-17

i have a list of dictionaries with missing values. I want to replace the empty value with the corresponding value by the more efficient way.

Input:

[
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://vimeo.com/42399207"},
]

Output:

[
    {"Host": "dailymotion", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "youtube", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "Vimeo", "Url": "https://vimeo.com/42399207"},
]

CodePudding user response:

You may

  • pair the first half (raw[:len(raw) // 2]) with the second half (raw[len(raw) // 2:]) using zip

  • then take the Host from one (d1['Host']), and the Url from the other (d2['Url'])

raw = [{'Host': 'dailymotion', 'Url': ''},
       {'Host': 'youtube', 'Url': ''},
       {'Host': 'Vimeo', 'Url': ''},
       {'Host': '', 'Url': 'https://www.dailymotion.com/video/x37j4ox'},
       {'Host': '', 'Url': 'https://www.youtube.com/watch?v=uDLQfA2o0'},
       {'Host': '', 'Url': 'https://vimeo.com/42399207'}]

result = [{'Host': d1['Host'], 'Url': d2['Url']}
          for d1, d2 in zip(raw[:len(raw) // 2], raw[len(raw) // 2:])]
print(result)

CodePudding user response:

Another solution:

lst = [
    {"Host": "dailymotion", "Url": ""},
    {"Host": "youtube", "Url": ""},
    {"Host": "Vimeo", "Url": ""},
    {"Host": "", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "", "Url": "https://vimeo.com/42399207"},
]

hosts = [d["Host"] for d in lst if d["Host"] != ""]
urls = [d["Url"] for d in lst if d["Url"] != ""]

out = [{"Host": h, "Url": u} for h, u in zip(hosts, urls)]
print(out)

Prints:

[
    {"Host": "dailymotion", "Url": "https://www.dailymotion.com/video/x37j4ox"},
    {"Host": "youtube", "Url": "https://www.youtube.com/watch?v=uDLQfA2o0"},
    {"Host": "Vimeo", "Url": "https://vimeo.com/42399207"},
]
  • Related