简体   繁体   English

如何使用循环基于键分配字典值

[英]How do you use loop to assign dictionary value based upon key

I am trying to loop through a list used to create dictionary keys and assign a value based upon a few different categories 我试图循环用于创建字典键的列表,并根据几个不同的类别分配值

For example: 例如:

list = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']

my_dict = {}

for i in range(len(list)):
     if any("cat" in s for s in list):
          my_dict[list[i]] = 'categorical'
     if any("num" in s for s in list):
          my_dict[list[i]] = 'numerical'  

I am trying to get a dictionary that would loop and result in: 我试图得到一个循环导致的字典:

my_dict = {'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'}

Thanks for any help! 谢谢你的帮助!

If you can assume that values in your list will match one of your lookups, you can do that like: 如果您可以假设列表中的值与您的某个查找匹配,则可以这样做:

items = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']
matches = {'num': 'numerical', 'cat': 'categorical'}
result = {i: [v for k, v in matches.items() if k in i][0] for i in items}
print(result)

How? 怎么样?

This uses a dict to map the desired search string to a matched values. 这使用dict将所需的搜索字符串映射到匹配的值。 It then uses a loop comprehension to search each value in the dict and returns the matched value. 然后,它使用循环理解来搜索dict中的每个值并返回匹配的值。 The value is used as the value in the dict comprehension. 该值用作dict理解中的值。

Results: 结果:

{'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical',
 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'
}

Stephen Rauch has a nice idea. Stephen Rauch有个好主意。 Here's a slightly more concise version of what he's written using dict.get . 这是使用dict.get编写的更简洁的版本。

matches = {'num': 'numerical', 'cat': 'categorical'}
result = {k : matches.get(k[:3], 'unknown') for k in items}

print(result)
{'cat1': 'categorical',
 'cat2': 'categorical',
 'cat3': 'categorical',
 'number1': 'numerical',
 'number2': 'numerical',
 'number3': 'numerical'}

If you want to drop values that do not match, make a slight modification: 如果要删除不匹配的值,请稍作修改:

result = {k : matches[k[:3]] for k in items if k[:3] in matches}

Here's my take on it. 这是我的看法。 Sort items first, and then find the index of discontinuity. 首先对items排序,然后找到不连续性的索引。

items.sort()

for i, l in enumerate(items):
    if l.startswith('num'):
        break

result = dict.fromkeys(items[:i], 'categorical')
result.update(dict.fromkeys(items[i:], 'numerical'))

This works best for two classes of values only. 这最适用于两类值。

print(result)
{'cat1': 'categorical',
 'cat2': 'categorical',
 'cat3': 'categorical',
 'number1': 'numerical',
 'number2': 'numerical',
 'number3': 'numerical'}

Your example is fairly close but has a few issues. 你的例子相当接近,但有一些问题。 Here is a solution that modifies your code as little as possible: 这是一个尽可能少地修改代码的解决方案:

lst = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']

my_dict = {}

for value in lst:
     if "cat" in value:
          my_dict[value] = 'categorical'
     if "num" in value:
          my_dict[value] = 'numerical'  

The first major issue is that you should never override a built-in. 第一个主要问题是你永远不应该覆盖内置的。 Use lst or list_ not list. 使用lst或list_ not list。

Now let's look at this bit of your code: 现在让我们看看你的代码:

if any("cat" in s for s in lst):

...as you have it, this checks if "cat" appears anywhere in the list (not just in the item you meant to check). ......就像你拥有它一样,这会检查“cat”是否出现在列表中的任何位置(而不仅仅是你要检查的项目)。

Since this is true, 'cat1' would be assigned to categorical. 由于这是真的,'cat1'将被分配到分类。 But because you have another if statement that also evals to true for numerical, this result is overwritten and you end up with all of the entries being listed as numerical. 但是因为你有另一个if语句也会因为数字而变为true,所以这个结果会被覆盖,你最终会将所有条目列为数字。

Change your code a little bit; 稍微改变你的代码; use startswith to look for a match: 使用startswith寻找匹配:

lst = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']

my_dict = {}

for x in lst:
    if x.startswith('cat'):
        my_dict[x] = 'categorical'
    elif x.startswith('num'):
        my_dict[x] = 'numerical'

print(my_dict)

# {'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'}

First, Try not to overwrite built-ins like str, list, etc.. with your variable/functions. 首先,尽量不要使用变量/函数覆盖str,list等内置函数。

A simple way to do it: 一个简单的方法:

some_elements = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']

my_dict = {}

for elt in some_elements:
    if "cat" in elt:
        my_dict[elt] = 'categorical'
    elif "num" in elt:
        my_dict[elt] = 'numerical'  

print(my_dict)

# {'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 
# 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'}

The simplest answer: 最简单的答案:

l = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3', 'junk']
d = {k: 'categorical' if 'cat' in k else 'numerical' if 'number' in k else 'unknown' for k in l}

Output: 输出:

{'cat1': 'categorical', 'cat2': 'categorical', 'cat3': 'categorical', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical', 'junk': 'unknown'}

Try using the dictionary setdefault function: 尝试使用字典setdefault函数:

l = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']
my_dict = {}
for i in l:
    my_dict.setdefault(i,['numerical' if 'number' in i else 'category'][-1])  
print(my_dict)

Output: 输出:

{'cat1': 'category', 'cat2': 'category', 'cat3': 'category', 'number1': 'numerical', 'number2': 'numerical', 'number3': 'numerical'}
list_ = ['cat1', 'cat2', 'cat3', 'number1', 'number2', 'number3']
# Don't name the variable "list" as it is a keyword if you can't think of anything else append a underscore at end

my_dict = {}

for item in list_:
    if "cat" in item:
        my_dict[item] = 'categorical'
    elif "number" in item:
        my_dict[item] = 'numerical'

print(my_dict)
import itertools
lst = [‘cat1’, ‘cat2’, ‘cat3’, ‘number1’, ‘number2’, ‘number3’]
values = [‘categorical’, ‘numerical’]

dict(filter(lambda item: item[0][:3] == item[1][:3], list(itertools.product(lst, values))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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