简体   繁体   中英

Create a new dictionary list from other lists?

I have a list of repeated words and another list of words not repeated as follows (They are all located in txt files):

file1.txt:
listRepeat = ['aaa','aaa', 'bbb', 'ccc', 'ddd', 'bbb', 'ddd']

file2.txt:
listRepeat = ['aaa','eee', 'bbb', 'eee', 'bbb', 'ddd']

and the following list that contains the non-repeated elements of the files:

listEND = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

I want to create a dictionary list as follows:

[{'file1.txt':['aaa':2], ['bbb':2], ['ccc':1], ['ddd':2], ['eee':0]}]
[{'file2.txt':['aaa':1], ['bbb':2], ['ccc':0], ['ddd':1], ['eee':2]}]

The idea is to populate my dictionary list with the elements of the file lists and say the number of these elements in the list of elements, just like the example above, but I'm not getting the construction of this dictionary right. My code looks like this:

for i in listEND:
        newllist.append({file:[i,listRepeat.count(i)]})

Where the newlist is the dictionary list, where it places the respective file as the dictionary key and as items the elements and their respective count in i . But the result is this below:

{'file1.txt': ['aaa', 2]}
{'file1.txt': ['bbb', 2]}
{'file1.txt': ['ccc', 1]}
...

and so on. Does anyone know where is wrong in the code?

Try this:

file1 = ['aaa','aaa', 'bbb', 'ccc', 'ddd', 'bbb', 'ddd']
file2 = ['aaa','eee', 'bbb', 'eee', 'bbb', 'ddd']

listEND = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

file_contents = {"file1.txt":file1, "file2.txt":file2}


new_list = {filename:{x:lst.count(x) for x in listEND} for filename, lst in file_contents.items()}
print(new_list)

Output:

{'file1.txt': {'aaa': 2, 'bbb': 2, 'ccc': 1, 'ddd': 2, 'eee': 0}, 'file2.txt': {'aaa': 1, 'bbb': 2, 'ccc': 0, 'ddd': 1, 'eee': 2}}

Your desired output is invalid. It looks like you actually want nested dicts:

{'file1.txt': {'aaa': 2, 'bbb': 2, 'ccc': 1, 'ddd': 2, 'eee': 0},
 'file2.txt': {'aaa': 1, 'bbb': 2, 'ccc': 0, 'ddd': 1, 'eee': 2}}

Making that happen in your code would look like this:

...
for i in listEND:
    newdict[file][i] = listRepeat.count(i)

But before this step you'll need to define newdict = {} and newdict[file] = {} .


BTW you could consider using collections.Counter instead, but it works a bit differently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM