尝试从网络抓取内容创建字典列表

时间:2021-02-24 04:39:31

标签: python

我是 Python 新手,但已经在 R 中工作了一段时间,但主要用于处理数据框。我在网上抓取了以下内容,其输出是下面包含的四个列表:但取出值以创建最小的可重现示例。

我正在尝试将这些放入字典列表中,以便按以下方式设置数据。

Each dictionary, rankings[i], should have these keys:

rankings[i]['name']: The name of the restaurant, a string.
rankings[i]['stars']: The star rating, as a string, e.g., '4.5', '4.0'
rankings[i]['numrevs']: The number of reviews, as an integer.
rankings[i]['price']: The price range, as dollar signs, e.g., '$', '$$', '$$$', or '$$$$'.

我对列表中的字典和一般的序列序列感到很困惑,所以如果你有任何很好的资源,请在这里链接它们!我一直在阅读 Think Python。

这就是我所拥有的,但它最终返回了一本包含值列表的字典,这不是我需要的。

非常感谢!

def Convert(tup, di): 
    for w, x,y,z in tup: 
        di.setdefault(w, []).extend((w,x,y,z))
    return di 
yelp = list(zip(name, stars, numrevs, price))
dictionary = {} 

output = Convert(yelp, dictionary)

#data
name = ['Mary Mac’s Tea Room', 'Busy Bee Cafe', 'Richards’ Southern Fried']

stars = ['4.0 ', '4.0 ', '4.0']

numrevs = ['80', '49', '549']

price = ['$$', '$$', '$$']


Update:

This will give me a dictionary of a single restaurant:

def 转换(tup, di): 字典 = {} 对于名称、星星、numrevs、tup 中的价格: yelp = list(zip(name, stars, numrevs, price))

name, stars, numrevs, price = tup[0]
entry = {"name"   : name,
     "stars"  : stars,
     "numrevs": numrevs,
     "print"  : price}
return entry

output = Convert(yelp, dictionary) 输出


This is my attempt to iterate over the all restaurants and add them to a list. It looks like I am only getting the final restaurant and everything else is being written over. Perhaps I need to do something like 

def 转换(tup, di): 字典 = {}

for name, stars, numrevs, price in tup: 
    yelp = list(zip(name, stars, numrevs, price))
    
for i in name, stars, numrevs, price:
    l = []
    entry = {"name"   : name,
         "stars"  : stars,
         "numrevs": numrevs,
         "price"  : price}
    l.append(entry)
return l

output = Convert(yelp, dictionary) 输出

1 个答案:

答案 0 :(得分:0)

您的函数中没有任何内容尝试以您想要的格式构建字典列表。您使用 extend 方法创建每个值。这增加了一个列表;它不会构造一个字典。

从内部开始:仅从第一组元素构建您想要的格式的单个字典。此外,使用有意义的变量名称——您是否希望其他人都学习您的单字母映射,这样您就可以节省几秒钟的输入时间?

name, stars, numrevs, price = tup[0]
entry = {"name"   : name,
         "stars"  : stars,
         "numrevs": numrevs,
         "print"  : price}

就是你如何为你的字典列表制作一个单独的字典。 这应该让你开始。现在您需要 (1) 学习将 entry 添加到列表中; (2) 遍历 tup 中的所有四元组(另一个要替换的无意义名称),以便您最终将每个条目添加到您返回的最终列表中。


更新第二个问题:

它不断覆盖,因为你明确告诉它这样做。每次循环时,您都将 l 重置为空列表。 停止!有很多地方可以向您展示如何在列表中累积迭代结果。首先将初始化提升到之前循环。

l = []
for ...