【问题标题】:How to add list of tuple value in list of dictionary using pyspark?如何使用pyspark在字典列表中添加元组值列表?
【发布时间】:2017-08-19 18:34:44
【问题描述】:

我有 2 个 rdd,一个作为字典列表,第二个作为元组列表,如下所示 -

rdd1 = [{'id1', ['string', 'string', count]}, {'id2', ['string', 'string', count]}, {'id3', ['string ', '字符串', 计数]}] rdd2 = [(id1, count), (id2, count), (id3, count)]

如果 rdd2 中的 id 与 rdd1 匹配,现在我想将 rdd2 的计数添加到 rdd1。 你能帮我实现这个吗?

提前谢谢你。

【问题讨论】:

    标签: list dictionary tuples pyspark rdd


    【解决方案1】:

    虽然盖茨的回答是正确的,但在使用 RDD 时,您应该尽量避免使用 for 循环。在处理大型数据集时,RDD 上的操作是并行化的,并且与 for 循环相比要快得多。您可以通过连接两个 RDD 并重新格式化输出来实现同样的效果:

    rdd1 = sc.parallelize([{'id1':['string','string',1]}, {'id2':['string','string',2]}, {'id3':['string','string',3]}])
    rdd2 = sc.parallelize([('id1',2), ('id2',4), ('id3',6), ('id4',8)])
    rdd_joined = rdd1.flatMap(lambda x:x.items()).join(rdd2)
    rdd_reformatted = rdd_joined.map(lambda (x,(y,z)):{x:y[:-1]+[y[-1]+z]})
    

    rdd_reformatted.collect() 作为输出:

    [{'id2': ['string', 'string', 6]}, 
     {'id3': ['string', 'string', 9]}, 
     {'id1': ['string', 'string', 3]}]
    

    【讨论】:

    • 谢谢雅科。你很棒。从您的代码中学到了很多东西。
    【解决方案2】:

    我希望这会有所帮助。

    rdd1 = [{'id1':['string','string',1]}, {'id2':['string','string',2]}, {'id3':['string','string',3]}]
    rdd2 = [('id1',2), ('id2',4), ('id3',6), ('id4',8)]
    
    for each in rdd2:
        there = False
        position = 0
        for ele in rdd1:
            if each[0] in ele.keys():
                #now increment the count
                original = rdd1[position]
                originalList = original[each[0]]
                #updating the 3rd element
                newList = originalList
                newList[2] = originalList[2] + each[1]
                #update the new list to key
                updated = { each[0] : newList }
                rdd1[position] = updated
                there = True
                break
            position = position + 1
    print rdd1
    #output: [{'id1': ['string', 'string', 3]}, {'id2': ['string', 'string', 6]}, {'id3': ['string', 'string', 9]}]
    

    【讨论】:

    • 非常感谢。这对我很有帮助。
    猜你喜欢
    • 2019-09-01
    • 2011-03-22
    • 2021-01-26
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多