解析字典键和值以及将数据写入/附加到文件

时间:2013-05-02 02:57:16

标签: python

我有以下内容,需要一些关于python实现的指导..我清楚地记录了算法和预期输出。所有输入都是真正的赞赏..

data_changes ={'305403': ['302180'], '312994': ['311957'], '311957': ['312621'] }
modem_changes = {'305403': [], '313113': [], '312994': ['253036', '312591'], '311957': []}

for keys that are present in both data_changes and modem_changes:
        write data to a file "file.txt" in the order key-->data_changes_values-->modem_changes_values

for keys that exist in only one of data_changes and modem_changes :
        append data to the same file "file.txt" key--> data_changes_values or key-->modem_changes values

EXPECTED OUTPUT:-

Create a text file with the following data

305403 302180
312994 311957 253036 312591
311957 312621
313113

以下是我尝试但不符合我的目的......

build_dep_list= [i
for k, v in itertools.chain.from_iterable(d.iteritems() for d in (data_changes, modem_changes))
for i in [k] + (v or [])
if i]
print "BUILD LIST"
print list(set(build_dep_list))

CURRENT OUTPUT:-
['305403', '302180', '313113', '311957', '312621', '253036', '312994', '312591']

2 个答案:

答案 0 :(得分:1)

使用set ...他们将有效地完成交叉点和对称差异的艰苦工作:

data_changes = {'305403': ['302180'], '312994': ['311957'], '311957': ['312621'] }
modem_changes = {'305403': [], '313113': [], '312994': ['253036', '312591'], '311957': []} 

dc_set = set(data_changes)
mc_set = set(modem_changes)

# open a file in append mode    
fh = open('myfile.txt', 'a')

for key in dc_set.intersection(mc_set):
    union_values = data_changes[key] + modem_changes[key]
    fh.write('%s,%s\n' % (key, ','.join(union_values)))

for key in dc_set.symmetric_difference(mc_set):
    dc_values = data_changes.get(key) or []
    mc_values = data_changes.get(key) or []
    union_values = dc_values + mc_values
    fh.write('%s,%s\n' % (key, ','.join(union_values)))

fh.close()

http://docs.python.org/2/library/sets.html

第一个是相当简单的,因为键都在两个词中。在另一种情况下,您不知道密钥将存在哪个字典。 get方法将尝试获取给定键的值,如果未找到则返回None。如果未找到,则默认为or语句中的空列表。

答案 1 :(得分:0)

for循环可写为:

with open('file.txt', 'r') as f:
    dc_keys = data_changes.keys()
    mc_keys = modem_changes.keys()

    for key in dc_keys:
        if key not in modem_changes.keys(): continue
        f.write('key-->' + ','.join(data_changes[key]) + '-->' + ','.join(modem_changes[key]) + '\n')

    for key in mc_keys:    
        if key in dc_keys: continue
        f.write('key-->' + ','.join(modem_changes[key]))

    for key in dc_keys:    
        if key in mc_keys: continue
        f.write('key-->' + ','.join(data_changes[key]))      

我已经更新了仅使用列表的答案,因为这更适合您的需求。至于文件写入,我已经更新它,以便它实际写入文件。