如何在python中从字典中打印2个或更多随机密钥

时间:2016-04-02 17:15:49

标签: python python-2.7 dictionary

    int postcode = 3000;
    String service = "Emergency";

    StringBuilder sb = new StringBuilder(); 
        sb.append("SELECT * FROM Hospital WHERE Postcode = ");
        sb.append(postcode);
        sb.append("AND Hospital_id IN SELECT Hospital_id FROM Hospital_Medical hm INNER JOIN "
                + "Medical_Service m ON hm.Medical_id = m.Medical_id where Medical_name = '");
        sb.append(service);
        sb.append("')");

    String queryString = sb.toString();
    Query query = em.createNativeQuery(queryString);
    List<Hospital> result = query.getResultList();

当我运行它时,它附带

build_dic = {}
with open (filedictionary, 'r') as df:
    for kv in [d.strip().split(':') for d in df]:
        build_dic[kv[0]] = kv[1]

for key in build_dic:
    key = random.sample(build_dic, n)
    print key

我该怎么办?我只想从我的dic中获得3个随机密钥。

1 个答案:

答案 0 :(得分:1)

不要使用循环。您循环遍历字典中的所有键,并在每次迭代中选择一个新样本。

只需使用random.sample()一次:

n = 3
random_keys = random.sample(build_dic, n)
print random_keys

当然,你可以循环random.sample()的结果。