2017-07-07 76 views
0

我有一個可變message是類型dict處理蟒字典

>>> print(message) 
{TopicPartition(topic='testing_topic', partition=1): [ConsumerRecord(topic='testing_topic', partition=1, offset=0, timestamp=1499411365748, timestamp_type=0, key=None, value=b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}', checksum=-309359221, serialized_key_size=-1, serialized_value_size=158)]} 

如何從它取回value部分。 我嘗試了很多,但我無法做到。請建議。

我想要這個。

value=b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}' 
+0

你嘗試'消息[0] [ '值']'?看起來這些值包含在一個列表中。 –

+0

我得到關鍵錯誤'print(message [0] ['value'])'KeyError:0 – Avi

+1

不知道這些'TopicPartition'和'ConsumerRecord'類是什麼,這很難說。但是你可以嘗試'next(iter(message.values()))[0] .value'。 –

回答

2

這就是所謂的命名元組

for i in message.values(): 
...  for j in i: 
...  print(j.value) 

完整代碼其他一些用戶想知道

from collections import namedtuple 

R = namedtuple('TopicPartition','topic partition') 
index = R(topic='testing_topic', partition=1) 

V = namedtuple('ConsumerRecord','topic partition offset timestamp timestamp_ 
type key value checksum serialized_key_size serialized_value_size') 

content = V(topic='testing_topic', partition=1, offset=0, timestamp=14994113 
65748, timestamp_type=0, key=None, value=b'{"url":"http://review.travel.rakuten. 
co.jp/hotel/voice/158886/", "meta":{"url_cnt":"1185","hotelid":"158886","job_id" 
:"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}', checksum=-309359221, serialized_key_ 
size=-1, serialized_value_size=158) 

D = {index:[content]} 

for i in D.values(): 
...  for j in i: 
...  print(j.value) 

b'{"url":"http://review.travel.rakuten.co.jp/hotel/voice/158886/", "meta":{"url_ 
cnt":"1185","hotelid":"158886","job_id":"0f3de6d4-34bf-4a1a-a803-5640e8d25932"}}