如何从Python词典列表创建三个单独的值列表,其中每个词典有三个键

时间:2016-09-11 22:41:27

标签: python list dictionary

我是Python新手。对于经验丰富的开发人员和编码人员来说,我的问题可能很简单,但我还没有找到答案。

我正在通过数据库查询检索一些数据。我成功地将查询返回的每一行组织为具有三个键和每个键的相应值的字典。基本上,我已将查询返回的所有数据行组织到字典列表中。

词典列表看起来有点像这样:

[
    {'Date': date1, 'price': price1, 'itemnumber': number1},
    {'Date': date2, 'price': price2, 'itemnumber': number2},
    ...
]

如何将此词典列表转换为对应于每个键的三个单独列表,即日期,价格和项目编号?

感谢您的帮助。

4 个答案:

答案 0 :(得分:5)

使用列表推导

// A structure to represent an adjacency list node
struct AdjListNode
{
    int dest;
    int weight;
    std::list<int> adjacents;
    struct AdjListNode* next;

    AdjListNode() : dest(0), weight(0), next(NULL) {}
};

// A structure to represent an adjacency list
struct AdjList
{
    int pos;
    struct AdjListNode *head; // pointer to head node of list

    // Initialize each adjacency list as empty by making head as NULL
    AdjList() : pos(0), head(NULL) {}
    ~AdjList()
      { while (head) {
          struct AdjListNode* temp = head;
          head = head->next;
          delete temp;
        }
      }

    void addAdjacent(int adjacent)
      { struct AdjListNode* newNode = new AdjListNode;
        newNode->next = head;
        head = newNode;
        newNode->adjacents.push_back(adjacent);
      }
};

// A structure to represent a graph. A graph is an array of adjacency lists.
// Size of array will be V (number of vertices in graph)
struct Graph
{
    int V;
    struct AdjList* array;

    // Create an array of adjacency lists. Size of array will be V
    Graph(int v) : V(v), array(NULL)
      { if (v >= 0 && v <= 1000)
          array = new struct AdjList[v];
        else
          throw std::bad_alloc();
      }
    ~Graph()
      { delete [] array; }
};

int main() {
   struct Graph* graph = new Graph(2);
   graph->array[0].addAdjacent(1);
   graph->array[1].addAdjacent(1);
   delete graph;
   return 0;
}

人们也可以用不太可读的内容来做到这一点:

date = [d['Date'] for d in list_of_dicts]
price = [d['price'] for d in list_of_dicts]
itemnumber = [d['itemnumber'] for d in list_of_dicts]

在第二种情况下,使用date, price, itemnumber = zip(*[(d['Date'], d['price'], d['itemnumber']) for d in list_of_dicts]) 将返回的元组转换为列表。

答案 1 :(得分:3)

你可以组合一个listcomp和一个dictcomp:

In [95]: ds
Out[95]: 
[{'Date': 'date1', 'itemnumber': 'number1', 'price': 'price1'},
 {'Date': 'date2', 'itemnumber': 'number2', 'price': 'price2'}]

In [96]: {key: [subdict[key] for subdict in ds] for key in ds[0]}
Out[96]: 
{'Date': ['date1', 'date2'],
 'itemnumber': ['number1', 'number2'],
 'price': ['price1', 'price2']}

请注意,我们有三个单独的列表,它们更方便地存储为字典中的值。这样,如果我们决定添加一个额外的特征(比如“购买者”),我们就不需要改变任何逻辑。

答案 2 :(得分:1)

# Defining lists
dates = []
prices = []
item_numbers = []
# Loop through list
for dictionary in your_list:
    dates.append(dictionary["Date"]) # Add the date to dates
    prices.append(dictionary["price"]) # Add the price to prices
    # Add item number to item_numbers
    item_numbers.append(dictionary["itemnumber"])

答案 3 :(得分:0)

for (field,values) in [(field,
            [result.get(field) for result in results]
        ) for field in results[0].keys()]:
    # this is ugly, but I can't see any other legal way to
    # dynamically set variables.
    eval "%s=%s" % (field, repr(value))

编辑不[非法]修改locals()词典:(