[英]Build a List of Tuples from a Dict
我有一個字典的鍵列表y
,該字典是從對Google Places API
的調用派生而來的。
我想為每個興趣點建立一個元組列表:
lst = []
for i in range(len(y)):
lst.append((y[i]['name'], y[i]['formatted_address'], y[i]['opening_hours']['open_now'], y[i]['rating']))
如果該字段在列表中,並且我收到的結果列表類似於下面的結果,則這是我想要的:
("Friedman's", '1187 Amsterdam Ave, New York, NY 10027, USA', True, 4.2)
但是,如果所需字段不在列表y
,則腳本將引發錯誤。 如何構建元組列表,以在構建元組之前檢查所需字段是否在y
?
這是我嘗試過的:
for i in range(len(y)):
t = ()
if y[i]['name']:
t = t + lst.append(y[i]['name'])
if y[i]['formatted_address']:
t = t + lst.append(y[i]['formatted_address'])
if y[i]['opening_hours']['open_now']:
t = t + lst.append(y[i]['opening_hours']['open_now'])
if y[i]['rating']:
t = t + lst.append(y[i]['rating'])
lst.append(t)
但是,這行不通,而且看起來很不雅致。 有什么建議么?
首先,您幾乎永遠都不要循環超出范圍(len(something))。 總是直接遍歷事物。 這大大減少了代碼的繁瑣。
對於實際問題,您可以遍歷鍵並僅在dict中添加項目。 使用嵌套查找的一個元素會使情況變得更加復雜,但是如果將其刪除,則代碼將變成:
for item in y:
lst.append(tuple(item[key] for key in ('name', 'formatted_address', 'opening_hours', 'rating') if key in item))
當其中一個鍵不存在時(使用dict.get()
),此列表理解將使用默認值。 我添加了變量,以便您可以設置所需的默認值。
default_name = ''
default_address = ''
default_open_now = False
default_rating = 0.0
new_list = [
(
e.get('name', default_name),
e.get('formatted_address', default_address),
e.get('opening_hours', {}).get('open_now', default_open_now),
e.get('rating', default_rating),
)
for e in y]
您可以使用dict
的get
功能。
y[i].get('name')
如果y[i]
具有鍵'name'
返回值或None
。 對於嵌套字典,請使用get
default
值。
y[i].get('opening_hours', {}).get('open_now')
對於數據結構,建議將其保留為字典,然后將字典添加到列表中。
lst = []
lst.append({'name': "Friedman's", "address": '1187 Amsterdam Ave, New York, NY 10027, USA'})
嘗試這個:
for i in y:
lst.append((v for k,v in i.items()))
您可以使用keys方法在字典中查找鍵。 在您的情況下:
lst=[]
fields = ('name', 'formatted_address', 'opening_hours' 'open_now', 'rating')
for i in range(len(y)):
data = []
for f in fields:
if f in y[].keys():
data.append(y[i][f])
else:
data.append(None)
lst.append(set(data))
請注意,您還可以使用items()方法獲取字典中所有鍵,值對。 那實際上只是簡單的代碼。 為了使它更好,請遍歷該集合,而不要調用len(set):
lst=[]
fields = ('name', 'formatted_address', 'opening_hours' 'open_now', 'rating')
for i in y:
data = []
for key, value in i.items():
if key in fields:
data.append(value)
else:
data.append(None)
lst.append(set(data))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.