dongsu4345 2017-01-17 13:43
浏览 164
已采纳

具有命名键的多维数组?

I'm learning Python by converting some old scripts from PHP to Python, and I'm stuck with something I can solve in PHP.

I have 3 lists of data (fetched via SNMP). In PHP, I'm storing them like so:

  $array['12345']['user'] = 'example@example.com';
  $array['12345']['int_id'] = 1;
  $array['12345']['int_speed'] = 1238745;

  $array['51245']['user'] = 'example@example.com';
  $array['51245']['int_id'] = 2;
  $array['51245']['int_speed'] = 5151244;

As I have 3 lists, I'm doing 3 sets of processing. The first run fetches a list of all usernames and user IDs (12345/51245 above), meaning I can set the first part of the array. I can then process the other two lists of data, and in PHP they'd be assigned like so (in a foreach, probably):

  $array[$user_id]['int_id'] = $int_id;
  $array[$user_id]['int_speed'] = $int_speed;

Trying to replicate this behaviour on Python is becoming quite tricky, I'm presuming what I want to do is create a dictionary of lists? But then I'm not sure how I add/edit these lists or cycle through them getting all the values of each layer of the array in turn.

  • 写回答

1条回答 默认 最新

  • duanlachu7344 2017-01-17 13:53
    关注

    There don't seem to be any lists here at all; this is just a nested dict. And the syntax is pretty much the same as in PHP.

    data = {}
    for user_id in user_data:
        data[user_id] = {}
        data[user_id]['int_id'] = 1
        data[user_id]['user'] = 'foo@bar.com'
    
        # or more simply
        data[user_id] = {'user': 'foo@bar.com', 'int_id': 1}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?